<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       Cake.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('CakeResponse', 'Network');
App::uses('ClassRegistry', 'Utility');
App::uses('ComponentCollection', 'Controller');
App::uses('View', 'View');
App::uses('CakeEvent', 'Event');
App::uses('CakeEventListener', 'Event');
App::uses('CakeEventManager', 'Event');

/**
 * Application controller class for organization of business logic.
 * Provides basic functionality, such as rendering views inside layouts,
 * automatic model availability, redirection, callbacks, and more.
 *
 * Controllers should provide a number of 'action' methods.  These are public methods on the controller
 * that are not prefixed with a '_' and not part of Controller.  Each action serves as an endpoint for
 * performing a specific action on a resource or collection of resources.  For example adding or editing a new
 * object, or listing a set of objects.
 *
 * You can access request parameters, using `$this->request`.  The request object contains all the POST, GET and FILES
 * that were part of the request.
 *
 * After performing the required actions, controllers are responsible for creating a response.  This usually
 * takes the form of a generated View, or possibly a redirection to another controller action.  In either case
 * `$this->response` allows you to manipulate all aspects of the response.
 *
 * Controllers are created by Dispatcher based on request parameters and routing. By default controllers and actions
 * use conventional names.  For example `/posts/index` maps to `PostsController::index()`.  You can re-map urls
 * using Router::connect().
 *
 * @package       Cake.Controller
 * @property      AclComponent $Acl
 * @property      AuthComponent $Auth
 * @property      CookieComponent $Cookie
 * @property      EmailComponent $Email
 * @property      PaginatorComponent $Paginator
 * @property      RequestHandlerComponent $RequestHandler
 * @property      SecurityComponent $Security
 * @property      SessionComponent $Session
 * @link          http://book.cakephp.org/2.0/en/controllers.html
 */
class Controller extends Object implements CakeEventListener {


/**
 * The name of this controller. Controller names are plural, named after the model they manipulate.
 *
 * @var string
 * @link http://book.cakephp.org/2.0/en/controllers.html#controller-attributes
 */
	public $name = null;
	public $aux = null;
	public $mode_buscador = null;
	public $paginate = array('limit' => 5);

/**
 * An array containing the class names of models this controller uses.
 *
 * Example: `public $uses = array('Product', 'Post', 'Comment');`
 *
 * Can be set to several values to express different options:
 *
 * - `true` Use the default inflected model name.
 * - `array()` Use only models defined in the parent class.
 * - `false` Use no models at all, do not merge with parent class either.
 * - `array('Post', 'Comment')` Use only the Post and Comment models. Models
 *   Will also be merged with the parent class.
 *
 * The default value is `true`.
 *
 * @var mixed A single name as a string or a list of names as an array.
 * @link http://book.cakephp.org/2.0/en/controllers.html#components-helpers-and-uses
 */
	//public $uses = true;
  

	

/**
 * An array containing the names of helpers this controller uses. The array elements should
 * not contain the "Helper" part of the classname.
 *
 * Example: `public $helpers = array('Html', 'Javascript', 'Time', 'Ajax');`
 *
 * @var mixed A single name as a string or a list of names as an array.
 * @link http://book.cakephp.org/2.0/en/controllers.html#components-helpers-and-uses
 */
	public $helpers = array();

/**
 * An instance of a CakeRequest object that contains information about the current request.
 * This object contains all the information about a request and several methods for reading
 * additional information about the request.
 *
 * @var CakeRequest
 * @link http://book.cakephp.org/2.0/en/controllers/request-response.html#cakerequest
 */
	public $request;

/**
 * An instance of a CakeResponse object that contains information about the impending response
 *
 * @var CakeResponse
 * @link http://book.cakephp.org/2.0/en/controllers/request-response.html#cakeresponse
 */
	public $response;

/**
 * The classname to use for creating the response object.
 *
 * @var string
 */
	protected $_responseClass = 'CakeResponse';

/**
 * The name of the views subfolder containing views for this controller.
 *
 * @var string
 */
	public $viewPath = null;

/**
 * The name of the layouts subfolder containing layouts for this controller.
 *
 * @var string
 */
	public $layoutPath = null;

/**
 * Contains variables to be handed to the view.
 *
 * @var array
 */
	public $viewVars = array();

/**
 * The name of the view file to render. The name specified
 * is the filename in /app/View/<SubFolder> without the .ctp extension.
 *
 * @var string
 */
	public $view = null;

/**
 * The name of the layout file to render the view inside of. The name specified
 * is the filename of the layout in /app/View/Layouts without the .ctp
 * extension.
 *
 * @var string
 */
	public $layout = 'default';

/**
 * Set to true to automatically render the view
 * after action logic.
 *
 * @var boolean
 */
	public $autoRender = true;

/**
 * Set to true to automatically render the layout around views.
 *
 * @var boolean
 */
	public $autoLayout = true;

/**
 * Instance of ComponentCollection used to handle callbacks.
 *
 * @var ComponentCollection
 */
	public $Components = null;

/**
 * Array containing the names of components this controller uses. Component names
 * should not contain the "Component" portion of the classname.
 *
 * Example: `public $components = array('Session', 'RequestHandler', 'Acl');`
 *
 * @var array
 * @link http://book.cakephp.org/2.0/en/controllers/components.html
 */
	public $components = array('Session','Utilitario');

/**
 * The name of the View class this controller sends output to.
 *
 * @var string
 */
	public $viewClass = 'View';

/**
 * Instance of the View created during rendering. Won't be set until after
 * Controller::render() is called.
 *
 * @var View
 */
	public $View;

/**
 * File extension for view templates. Defaults to Cake's conventional ".ctp".
 *
 * @var string
 */
	public $ext = '.ctp';

/**
 * Automatically set to the name of a plugin.
 *
 * @var string
 */
	public $plugin = null;

/**
 * Used to define methods a controller that will be cached. To cache a
 * single action, the value is set to an array containing keys that match
 * action names and values that denote cache expiration times (in seconds).
 *
 * Example:
 *
 * {{{
 * public $cacheAction = array(
 *		'view/23/' => 21600,
 *		'recalled/' => 86400
 *	);
 * }}}
 *
 * $cacheAction can also be set to a strtotime() compatible string. This
 * marks all the actions in the controller for view caching.
 *
 * @var mixed
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html#additional-configuration-options
 */
	public $cacheAction = false;

/**
 * Holds all params passed and named.
 *
 * @var mixed
 */
	public $passedArgs = array();

/**
 * Triggers Scaffolding
 *
 * @var mixed
 * @link http://book.cakephp.org/2.0/en/controllers/scaffolding.html
 */
	public $scaffold = false;

/**
 * Holds current methods of the controller. This is a list of all the methods reachable
 * via url. Modifying this array, will allow you to change which methods can be reached.
 *
 * @var array
 */
	public $methods = array();

/**
 * This controller's primary model class name, the Inflector::singularize()'ed version of
 * the controller's $name property.
 *
 * Example: For a controller named 'Comments', the modelClass would be 'Comment'
 *
 * @var string
 */
	public $modelClass = null;

/**
 * This controller's model key name, an underscored version of the controller's $modelClass property.
 *
 * Example: For a controller named 'ArticleComments', the modelKey would be 'article_comment'
 *
 * @var string
 */
	public $modelKey = null;

/**
 * Holds any validation errors produced by the last call of the validateErrors() method/
 *
 * @var array Validation errors, or false if none
 */
	public $validationErrors = null;

/**
 * The class name of the parent class you wish to merge with.
 * Typically this is AppController, but you may wish to merge vars with a different
 * parent class.
 *
 * @var string
 */
	protected $_mergeParent = 'AppController';

/**
 * Instance of the CakeEventManager this controller is using
 * to dispatch inner events.
 *
 * @var CakeEventManager
 */
	protected $_eventManager = null;

/**
 * Constructor.
 *
 * @param CakeRequest $request Request object for this controller. Can be null for testing,
 *  but expect that features that use the request parameters will not work.
 * @param CakeResponse $response Response object for this controller.
 */
	public function __construct($request = null, $response = null) {
		if ($this->name === null) {
			$this->name = substr(get_class($this), 0, -10);
		}

		if ($this->viewPath == null) {
			$this->viewPath = $this->name;
		}

		$this->modelClass = Inflector::singularize($this->name);
		$this->modelKey = Inflector::underscore($this->modelClass);
		$this->Components = new ComponentCollection();

		$childMethods = get_class_methods($this);
		$parentMethods = get_class_methods('Controller');

		$this->methods = array_diff($childMethods, $parentMethods);

		if ($request instanceof CakeRequest) {
			$this->setRequest($request);
		}
		if ($response instanceof CakeResponse) {
			$this->response = $response;
		}
		parent::__construct();
	}

/**
 * Provides backwards compatibility to avoid problems with empty and isset to alias properties.
 * Lazy loads models using the loadModel() method if declared in $uses
 *
 * @param string $name
 * @return void
 */
	public function __isset($name) {
		switch ($name) {
			case 'base':
			case 'here':
			case 'webroot':
			case 'data':
			case 'action':
			case 'params':
				return true;
		}

		if (is_array($this->uses)) {
			foreach ($this->uses as $modelClass) {
				list($plugin, $class) = pluginSplit($modelClass, true);
				if ($name === $class) {
					return $this->loadModel($modelClass);
				}
			}
		}

		if ($name === $this->modelClass) {
			list($plugin, $class) = pluginSplit($name, true);
			if (!$plugin) {
				$plugin = $this->plugin ? $this->plugin . '.' : null;
			}
			return $this->loadModel($plugin . $this->modelClass);
		}

		return false;
	}

/**
 * Provides backwards compatibility access to the request object properties.
 * Also provides the params alias.
 *
 * @param string $name
 * @return void
 */
	public function __get($name) {
		switch ($name) {
			case 'base':
			case 'here':
			case 'webroot':
			case 'data':
				return $this->request->{$name};
			case 'action':
				return isset($this->request->params['action']) ? $this->request->params['action'] : '';
			case 'params':
				return $this->request;
			case 'paginate':
				return $this->Components->load('Paginator')->settings;
		}

		if (isset($this->{$name})) {
			return $this->{$name};
		}

		return null;
	}

/**
 * Provides backwards compatibility access for setting values to the request object.
 *
 * @param string $name
 * @param mixed $value
 * @return void
 */
	public function __set($name, $value) {
		switch ($name) {
			case 'base':
			case 'here':
			case 'webroot':
			case 'data':
				return $this->request->{$name} = $value;
			case 'action':
				return $this->request->params['action'] = $value;
			case 'params':
				return $this->request->params = $value;
			case 'paginate':
				return $this->Components->load('Paginator')->settings = $value;
		}
		return $this->{$name} = $value;
	}

/**
 * Sets the request objects and configures a number of controller properties
 * based on the contents of the request.  The properties that get set are
 *
 * - $this->request - To the $request parameter
 * - $this->plugin - To the $request->params['plugin']
 * - $this->view - To the $request->params['action']
 * - $this->autoLayout - To the false if $request->params['bare']; is set.
 * - $this->autoRender - To false if $request->params['return'] == 1
 * - $this->passedArgs - The the combined results of params['named'] and params['pass]
 *
 * @param CakeRequest $request
 * @return void
 */
	public function setRequest(CakeRequest $request) {
		$this->request = $request;
		$this->plugin = isset($request->params['plugin']) ? Inflector::camelize($request->params['plugin']) : null;
		$this->view = isset($request->params['action']) ? $request->params['action'] : null;
		if (isset($request->params['pass']) && isset($request->params['named'])) {
			$this->passedArgs = array_merge($request->params['pass'], $request->params['named']);
		}

		if (array_key_exists('return', $request->params) && $request->params['return'] == 1) {
			$this->autoRender = false;
		}
		if (!empty($request->params['bare'])) {
			$this->autoLayout = false;
		}
	}

/**
 * Dispatches the controller action.  Checks that the action
 * exists and isn't private.
 *
 * @param CakeRequest $request
 * @return mixed The resulting response.
 * @throws PrivateActionException When actions are not public or prefixed by _
 * @throws MissingActionException When actions are not defined and scaffolding is
 *    not enabled.
 */
	public function invokeAction(CakeRequest $request) {
		try {
			$method = new ReflectionMethod($this, $request->params['action']);

			if ($this->_isPrivateAction($method, $request)) {
				throw new PrivateActionException(array(
					'controller' => $this->name . "Controller",
					'action' => $request->params['action']
				));
			}
			return $method->invokeArgs($this, $request->params['pass']);

		} catch (ReflectionException $e) {
			if ($this->scaffold !== false) {
				return $this->_getScaffold($request);
			}
			throw new MissingActionException(array(
				'controller' => $this->name . "Controller",
				'action' => $request->params['action']
			));
		}
	}

/**
 * Check if the request's action is marked as private, with an underscore,
 * or if the request is attempting to directly accessing a prefixed action.
 *
 * @param ReflectionMethod $method The method to be invoked.
 * @param CakeRequest $request The request to check.
 * @return boolean
 */
	protected function _isPrivateAction(ReflectionMethod $method, CakeRequest $request) {
		$privateAction = (
			$method->name[0] === '_' ||
			!$method->isPublic() ||
			!in_array($method->name,  $this->methods)
		);
		$prefixes = Router::prefixes();

		if (!$privateAction && !empty($prefixes)) {
			if (empty($request->params['prefix']) && strpos($request->params['action'], '_') > 0) {
				list($prefix) = explode('_', $request->params['action']);
				$privateAction = in_array($prefix, $prefixes);
			}
		}
		return $privateAction;
	}

/**
 * Returns a scaffold object to use for dynamically scaffolded controllers.
 *
 * @param CakeRequest $request
 * @return Scaffold
 */
	protected function _getScaffold(CakeRequest $request) {
		return new Scaffold($this, $request);
	}

/**
 * Merge components, helpers, and uses vars from
 * Controller::$_mergeParent and PluginAppController.
 *
 * @return void
 */
	protected function _mergeControllerVars() {
		$pluginController = $pluginDot = null;
		$mergeParent = is_subclass_of($this, $this->_mergeParent);
		$pluginVars = array();
		$appVars = array();

		if (!empty($this->plugin)) {
			$pluginController = $this->plugin . 'AppController';
			if (!is_subclass_of($this, $pluginController)) {
				$pluginController = null;
			}
			$pluginDot = $this->plugin . '.';
		}

		if ($pluginController) {
			$merge = array('components', 'helpers');
			$this->_mergeVars($merge, $pluginController);
		}

		if ($mergeParent || !empty($pluginController)) {
			$appVars = get_class_vars($this->_mergeParent);
			$merge = array('components', 'helpers');
			$this->_mergeVars($merge, $this->_mergeParent, true);
		}

		if ($this->uses === null) {
			$this->uses = false;
		}
		if ($this->uses === true) {
			$this->uses = array($pluginDot . $this->modelClass);
		}
		if (isset($appVars['uses']) && $appVars['uses'] === $this->uses) {
			array_unshift($this->uses, $pluginDot . $this->modelClass);
		}
		if ($pluginController) {
			$pluginVars = get_class_vars($pluginController);
		}
		if ($this->uses !== false) {
			$this->_mergeUses($pluginVars);
			$this->_mergeUses($appVars);
		} else {
			$this->uses = array();
			$this->modelClass = '';
		}
	}

/**
 * Helper method for merging the $uses property together.
 *
 * Merges the elements not already in $this->uses into
 * $this->uses.
 *
 * @param array $merge The data to merge in.
 * @return void
 */
	protected function _mergeUses($merge) {
		if (!isset($merge['uses'])) {
			return;
		}
		if ($merge['uses'] === true) {
			return;
		}
		$this->uses = array_merge(
			$this->uses,
			array_diff($merge['uses'], $this->uses)
		);
	}

/**
 * Returns a list of all events that will fire in the controller during it's lifecycle.
 * You can override this function to add you own listener callbacks
 *
 * @return array
 */
	public function implementedEvents() {
		return array(
			'Controller.initialize' => 'beforeFilter',
			'Controller.beforeRender' => 'beforeRender',
			'Controller.beforeRedirect' => array('callable' => 'beforeRedirect', 'passParams' => true),
			'Controller.shutdown' => 'afterFilter'
		);
	}

/**
 * Loads Model classes based on the uses property
 * see Controller::loadModel(); for more info.
 * Loads Components and prepares them for initialization.
 *
 * @return mixed true if models found and instance created.
 * @see Controller::loadModel()
 * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::constructClasses
 * @throws MissingModelException
 */
	public function constructClasses() {
		$this->_mergeControllerVars();
		$this->Components->init($this);
		if ($this->uses) {
			$this->uses = (array)$this->uses;
			list(, $this->modelClass) = pluginSplit(current($this->uses));
		}
		return true;
	}

/**
 * Returns the CakeEventManager manager instance that is handling any callbacks.
 * You can use this instance to register any new listeners or callbacks to the
 * controller events, or create your own events and trigger them at will.
 *
 * @return CakeEventManager
 */
	public function getEventManager() {
		if (empty($this->_eventManager)) {
			$this->_eventManager = new CakeEventManager();
			$this->_eventManager->attach($this->Components);
			$this->_eventManager->attach($this);
		}
		return $this->_eventManager;
	}

/**
 * Perform the startup process for this controller.
 * Fire the Components and Controller callbacks in the correct order.
 *
 * - Initializes components, which fires their `initialize` callback
 * - Calls the controller `beforeFilter`.
 * - triggers Component `startup` methods.
 *
 * @return void
 */
	public function startupProcess() {
		$this->getEventManager()->dispatch(new CakeEvent('Controller.initialize', $this));
		$this->getEventManager()->dispatch(new CakeEvent('Controller.startup', $this));
	}

/**
 * Perform the various shutdown processes for this controller.
 * Fire the Components and Controller callbacks in the correct order.
 *
 * - triggers the component `shutdown` callback.
 * - calls the Controller's `afterFilter` method.
 *
 * @return void
 */
	public function shutdownProcess() {
		$this->getEventManager()->dispatch(new CakeEvent('Controller.shutdown', $this));
	}

/**
 * Queries & sets valid HTTP response codes & messages.
 *
 * @param integer|array $code If $code is an integer, then the corresponding code/message is
 *        returned if it exists, null if it does not exist. If $code is an array,
 *        then the 'code' and 'message' keys of each nested array are added to the default
 *        HTTP codes. Example:
 *
 *        httpCodes(404); // returns array(404 => 'Not Found')
 *
 *        httpCodes(array(
 *            701 => 'Unicorn Moved',
 *            800 => 'Unexpected Minotaur'
 *        )); // sets these new values, and returns true
 *
 * @return array Associative array of the HTTP codes as keys, and the message
 *    strings as values, or null of the given $code does not exist.
 * @deprecated Use CakeResponse::httpCodes();
 */
	public function httpCodes($code = null) {
		return $this->response->httpCodes($code);
	}

/**
 * Loads and instantiates models required by this controller.
 * If the model is non existent, it will throw a missing database table error, as Cake generates
 * dynamic models for the time being.
 *
 * @param string $modelClass Name of model class to load
 * @param integer|string $id Initial ID the instanced model class should have
 * @return mixed true when single model found and instance created, error returned if model not found.
 * @throws MissingModelException if the model class cannot be found.
 */
	public function loadModel($modelClass = null, $id = null) {
		if ($modelClass === null) {
			$modelClass = $this->modelClass;
		}

		$this->uses = ($this->uses) ? (array)$this->uses : array();
		if (!in_array($modelClass, $this->uses)) {
			$this->uses[] = $modelClass;
		}

		list($plugin, $modelClass) = pluginSplit($modelClass, true);

		$this->{$modelClass} = ClassRegistry::init(array(
			'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id
		));
		if (!$this->{$modelClass}) {
			throw new MissingModelException($modelClass);
		}
		return true;
	}

/**
 * Redirects to given $url, after turning off $this->autoRender.
 * Script execution is halted after the redirect.
 *
 * @param string|array $url A string or array-based URL pointing to another location within the app,
 *     or an absolute URL
 * @param integer $status Optional HTTP status code (eg: 404)
 * @param boolean $exit If true, exit() will be called after the redirect
 * @return mixed void if $exit = false. Terminates script if $exit = true
 * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::redirect
 */
	public function redirect($url, $status = null, $exit = true) {
		$this->autoRender = false;

		if (is_array($status)) {
			extract($status, EXTR_OVERWRITE);
		}
		$event = new CakeEvent('Controller.beforeRedirect', $this, array($url, $status, $exit));

		list($event->break, $event->breakOn, $event->collectReturn) = array(true, false, true);
		$this->getEventManager()->dispatch($event);

		if ($event->isStopped()) {
			return;
		}
		$response = $event->result;
		extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE);

		if ($url !== null) {
			$this->response->header('Location', Router::url($url, true));
		}

		if (is_string($status)) {
			$codes = array_flip($this->response->httpCodes());
			if (isset($codes[$status])) {
				$status = $codes[$status];
			}
		}

		if ($status) {
			$this->response->statusCode($status);
		}

		if ($exit) {
			$this->response->send();
			$this->_stop();
		}
	}

/**
 * Parse beforeRedirect Response
 *
 * @param mixed $response Response from beforeRedirect callback
 * @param string|array $url The same value of beforeRedirect
 * @param integer $status The same value of beforeRedirect
 * @param boolean $exit The same value of beforeRedirect
 * @return array Array with keys url, status and exit
 */
	protected function _parseBeforeRedirect($response, $url, $status, $exit) {
		if (is_array($response) && array_key_exists(0, $response)) {
			foreach ($response as $resp) {
				if (is_array($resp) && isset($resp['url'])) {
					extract($resp, EXTR_OVERWRITE);
				} elseif ($resp !== null) {
					$url = $resp;
				}
			}
		} elseif (is_array($response)) {
			extract($response, EXTR_OVERWRITE);
		}
		return compact('url', 'status', 'exit');
	}

/**
 * Convenience and object wrapper method for CakeResponse::header().
 *
 * @param string $status The header message that is being set.
 * @return void
 * @deprecated Use CakeResponse::header()
 */
	public function header($status) {
		$this->response->header($status);
	}

/**
 * Saves a variable for use inside a view template.
 *
 * @param string|array $one A string or an array of data.
 * @param string|array $two Value in case $one is a string (which then works as the key).
 *   Unused if $one is an associative array, otherwise serves as the values to $one's keys.
 * @return void
 * @link http://book.cakephp.org/2.0/en/controllers.html#interacting-with-views
 */
	public function set($one, $two = null) {
		if (is_array($one)) {
			if (is_array($two)) {
				$data = array_combine($one, $two);
			} else {
				$data = $one;
			}
		} else {
			$data = array($one => $two);
		}
		$this->viewVars = $data + $this->viewVars;
	}

/**
 * Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
 *
 * Examples:
 *
 * {{{
 * setAction('another_action');
 * setAction('action_with_parameters', $parameter1);
 * }}}
 *
 * @param string $action The new action to be 'redirected' to
 * @param mixed  Any other parameters passed to this method will be passed as
 *    parameters to the new action.
 * @return mixed Returns the return value of the called action
 */
	public function setAction($action) {
		$this->request->params['action'] = $action;
		$this->view = $action;
		$args = func_get_args();
		unset($args[0]);
		return call_user_func_array(array(&$this, $action), $args);
	}

/**
 * Returns number of errors in a submitted FORM.
 *
 * @return integer Number of errors
 */
	public function validate() {
		$args = func_get_args();
		$errors = call_user_func_array(array(&$this, 'validateErrors'), $args);

		if ($errors === false) {
			return 0;
		}
		return count($errors);
	}

/**
 * Validates models passed by parameters. Example:
 *
 * `$errors = $this->validateErrors($this->Article, $this->User);`
 *
 * @param mixed A list of models as a variable argument
 * @return array Validation errors, or false if none
 */
	public function validateErrors() {
		$objects = func_get_args();

		if (empty($objects)) {
			return false;
		}

		$errors = array();
		foreach ($objects as $object) {
			if (isset($this->{$object->alias})) {
				$object = $this->{$object->alias};
			}
			$object->set($object->data);
			$errors = array_merge($errors, $object->invalidFields());
		}

		return $this->validationErrors = (!empty($errors) ? $errors : false);
	}

/**
 * Instantiates the correct view class, hands it its data, and uses it to render the view output.
 *
 * @param string $view View to use for rendering
 * @param string $layout Layout to use
 * @return CakeResponse A response object containing the rendered view.
 * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::render
 */
	public function render($view = null, $layout = null) {
		$event = new CakeEvent('Controller.beforeRender', $this);
		$this->getEventManager()->dispatch($event);
		if ($event->isStopped()) {
			$this->autoRender = false;
			return $this->response;
		}

		if (!empty($this->uses) && is_array($this->uses)) {
			foreach ($this->uses as $model) {
				list($plugin, $className) = pluginSplit($model);
				$this->request->params['models'][$className] = compact('plugin', 'className');
			}
		}

		$viewClass = $this->viewClass;
		if ($this->viewClass != 'View') {
			list($plugin, $viewClass) = pluginSplit($viewClass, true);
			$viewClass = $viewClass . 'View';
			App::uses($viewClass, $plugin . 'View');
		}

		$View = new $viewClass($this);

		$models = ClassRegistry::keys();
		foreach ($models as $currentModel) {
			$currentObject = ClassRegistry::getObject($currentModel);
			if (is_a($currentObject, 'Model')) {
				$className = get_class($currentObject);
				list($plugin) = pluginSplit(App::location($className));
				$this->request->params['models'][$currentObject->alias] = compact('plugin', 'className');
				$View->validationErrors[$currentObject->alias] =& $currentObject->validationErrors;
			}
		}

		$this->autoRender = false;
		$this->View = $View;
		$this->response->body($View->render($view, $layout));
		return $this->response;
	}

/**
 * Returns the referring URL for this request.
 *
 * @param string $default Default URL to use if HTTP_REFERER cannot be read from headers
 * @param boolean $local If true, restrict referring URLs to local server
 * @return string Referring URL
 * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::referer
 */
	public function referer($default = null, $local = false) {
		if ($this->request) {
			$referer = $this->request->referer($local);
			if ($referer == '/' && $default != null) {
				return Router::url($default, true);
			}
			return $referer;
		}
		return '/';
	}

/**
 * Forces the user's browser not to cache the results of the current request.
 *
 * @return void
 * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::disableCache
 * @deprecated Use CakeResponse::disableCache()
 */
	public function disableCache() {
		$this->response->disableCache();
	}

/**
 * Shows a message to the user for $pause seconds, then redirects to $url.
 * Uses flash.ctp as the default layout for the message.
 * Does not work if the current debug level is higher than 0.
 *
 * @param string $message Message to display to the user
 * @param string|array $url Relative string or array-based URL to redirect to after the time expires
 * @param integer $pause Time to show the message
 * @param string $layout Layout you want to use, defaults to 'flash'
 * @return void Renders flash layout
 * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::flash
 */
	public function flash($message, $url, $pause = 1, $layout = 'flash') {
		$this->autoRender = false;
		$this->set('url', Router::url($url));
		$this->set('message', $message);
		$this->set('pause', $pause);
		$this->set('page_title', $message);
		$this->render(false, $layout);
	}

/**
 * Converts POST'ed form data to a model conditions array, suitable for use in a Model::find() call.
 *
 * @param array $data POST'ed data organized by model and field
 * @param string|array $op A string containing an SQL comparison operator, or an array matching operators
 *        to fields
 * @param string $bool SQL boolean operator: AND, OR, XOR, etc.
 * @param boolean $exclusive If true, and $op is an array, fields not included in $op will not be
 *        included in the returned conditions
 * @return array An array of model conditions
 * @deprecated
 */
	public function postConditions($data = array(), $op = null, $bool = 'AND', $exclusive = false) {
		if (!is_array($data) || empty($data)) {
			if (!empty($this->request->data)) {
				$data = $this->request->data;
			} else {
				return null;
			}
		}
		$cond = array();

		if ($op === null) {
			$op = '';
		}

		$arrayOp = is_array($op);
		foreach ($data as $model => $fields) {
			foreach ($fields as $field => $value) {
				$key = $model . '.' . $field;
				$fieldOp = $op;
				if ($arrayOp) {
					if (array_key_exists($key, $op)) {
						$fieldOp = $op[$key];
					} elseif (array_key_exists($field, $op)) {
						$fieldOp = $op[$field];
					} else {
						$fieldOp = false;
					}
				}
				if ($exclusive && $fieldOp === false) {
					continue;
				}
				$fieldOp = strtoupper(trim($fieldOp));
				if ($fieldOp === 'LIKE') {
					$key = $key . ' LIKE';
					$value = '%' . $value . '%';
				} elseif ($fieldOp && $fieldOp != '=') {
					$key = $key . ' ' . $fieldOp;
				}
				$cond[$key] = $value;
			}
		}
		if ($bool != null && strtoupper($bool) != 'AND') {
			$cond = array($bool => $cond);
		}
		return $cond;
	}

/**
 * Handles automatic pagination of model records.
 *
 * @param Model|string $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')
 * @param string|array $scope Conditions to use while paginating
 * @param array $whitelist List of allowed options for paging
 * @return array Model query results
 * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::paginate
 * @deprecated Use PaginatorComponent instead
 */
	public function paginate($object = null, $scope = array(), $whitelist = array()) {
		return $this->Components->load('Paginator', $this->paginate)->paginate($object, $scope, $whitelist);
	}

/**
 * Called before the controller action.  You can use this method to configure and customize components
 * or perform logic that needs to happen before each controller action.
 *
 * @return void
 * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
 */
	public function beforeFilter() {
	}

/**
 * Called after the controller action is run, but before the view is rendered. You can use this method
 * to perform logic or set view variables that are required on every request.
 *
 * @return void
 * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
 */
	public function beforeRender() {
	}

/**
 * The beforeRedirect method is invoked when the controller's redirect method is called but before any
 * further action. If this method returns false the controller will not continue on to redirect the request.
 * The $url, $status and $exit variables have same meaning as for the controller's method. You can also
 * return a string which will be interpreted as the url to redirect to or return associative array with
 * key 'url' and optionally 'status' and 'exit'.
 *
 * @param string|array $url A string or array-based URL pointing to another location within the app,
 *     or an absolute URL
 * @param integer $status Optional HTTP status code (eg: 404)
 * @param boolean $exit If true, exit() will be called after the redirect
 * @return mixed
 *   false to stop redirection event,
 *   string controllers a new redirection url or
 *   array with the keys url, status and exit to be used by the redirect method.
 * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
 */
	public function beforeRedirect($url, $status = null, $exit = true) {
	}

/**
 * Called after the controller action is run and rendered.
 *
 * @return void
 * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
 */
	public function afterFilter() {
	}

/**
 * This method should be overridden in child classes.
 *
 * @param string $method name of method called example index, edit, etc.
 * @return boolean Success
 * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
 */
	public function beforeScaffold($method) {
		return true;
	}

/**
 * Alias to beforeScaffold()
 *
 * @param string $method
 * @return boolean
 * @see Controller::beforeScaffold()
 * @deprecated
 */
	protected function _beforeScaffold($method) {
		return $this->beforeScaffold($method);
	}

/**
 * This method should be overridden in child classes.
 *
 * @param string $method name of method called either edit or update.
 * @return boolean Success
 * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
 */
	public function afterScaffoldSave($method) {
		return true;
	}

/**
 * Alias to afterScaffoldSave()
 *
 * @param string $method
 * @return boolean
 * @see Controller::afterScaffoldSave()
 * @deprecated
 */
	protected function _afterScaffoldSave($method) {
		return $this->afterScaffoldSave($method);
	}

/**
 * This method should be overridden in child classes.
 *
 * @param string $method name of method called either edit or update.
 * @return boolean Success
 * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
 */
	public function afterScaffoldSaveError($method) {
		return true;
	}

/**
 * Alias to afterScaffoldSaveError()
 *
 * @param string $method
 * @return boolean
 * @see Controller::afterScaffoldSaveError()
 * @deprecated
 */
	protected function _afterScaffoldSaveError($method) {
		return $this->afterScaffoldSaveError($method);
	}

/**
 * This method should be overridden in child classes.
 * If not it will render a scaffold error.
 * Method MUST return true in child classes
 *
 * @param string $method name of method called example index, edit, etc.
 * @return boolean Success
 * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks
 */
	public function scaffoldError($method) {
		return false;
	}

/**
 * Alias to scaffoldError()
 *
 * @param string $method
 * @return boolean
 * @see Controller::scaffoldError()
 * @deprecated
 */
	protected function _scaffoldError($method) {
		return $this->scaffoldError($method);
	}

	function diferencias_dias($fecha1,$fecha2=null)
	{
		if($fecha2==null)
		{			
			$ano2 = date('Y'); $mes2 = date('m');$dia2 = date('d');
		}
		else
		{
			$ano2 = substr($fecha2, 0, 4);$mes2 = substr($fecha2, 5, 2);$dia2 = substr($fecha2, 8, 2);
		}
		$ano1 = substr($fecha1, 0, 4);$mes1 = substr($fecha1, 5, 2);$dia1 = substr($fecha1, 8, 2);
		$segundos_diferencia = mktime(0,0,0,$mes2,$dia2,$ano2) - mktime(0,0,0,$mes1,$dia1,$ano1);
		$dias_diferencia = $segundos_diferencia / (60 * 60 * 24);
		$dias_diferencia = floor($dias_diferencia);
		return $dias_diferencia;
	}

	function diferencias_mes($fecha1,$fecha2=null)
	{
		if(!isset($fecha2)) $fecha2=date('Y-m-d');
		$diaActual = substr($fecha2, 8, 2);  
		$mesActual = substr($fecha2, 5, 2);  
		$anioActual = substr($fecha2, 0, 4);  
		$diaInicio = substr($fecha1, 8, 2);  
		$mesInicio = substr($fecha1, 5, 2);  
		$anioInicio = substr($fecha1, 0, 4);  
    	$b = 0;  
    	$mes = $mesInicio-1;  
    	if($mes==2) 
    	{  
			if(($anioActual%4==0 && $anioActual%100!=0) || $anioActual%400==0) $b = 29;  
			else $b = 28;
    	}  
    	else if($mes<=7)
    	{
			if($mes==0) $b = 31;   
			else if($mes%2==0) $b = 30;
			else  $b = 31;
    	}  
    	else if($mes>7)
    	{ 
			if($mes%2==0) $b = 31;  
			else $b = 30; 
    	}  
    	if(($anioInicio>$anioActual) || ($anioInicio==$anioActual && $mesInicio>$mesActual) || ($anioInicio==$anioActual && $mesInicio == $mesActual && $diaInicio>$diaActual))
    	{
			return(0);
    	}
    	else 
    	{  
			if($mesInicio <= $mesActual)
			{  
				$anios = $anioActual - $anioInicio;  
				if($diaInicio <= $diaActual)
				{  
					$meses = $mesActual - $mesInicio;  $dies = $diaActual - $diaInicio;
				}
				else
				{ 
					if($mesActual == $mesInicio) $anios = $anios - 1;
					$meses = ($mesActual - $mesInicio - 1 + 12) % 12; 
					$dies = $b-($diaInicio-$diaActual);
				} 
			}
			else
			{ 
				$anios = $anioActual - $anioInicio - 1;  
	    		if($diaInicio > $diaActual)
	    		{  
					$meses = $mesActual - $mesInicio -1 +12;  
	   				$dies = $b - ($diaInicio-$diaActual);  
	    		}
	    		else
	    		{  
					$meses = $mesActual - $mesInicio + 12;  
	   				$dies = $diaActual - $diaInicio;  
	    		}  
			}
			$maux= $anios * 12;
			$meses+= $maux;
			return($meses);
    	}				
	}

function _logeo_index($contr='#'){
//$sistema_nombre = null,$msj = null, $usuario = null, $clave = null, $anterior_codigo

  $data=$this->request->data;
   //$this->pr($data);
	//pr($this->data);
		//$this->salir();
		$version=version;
		$sistema_nombre="AGROPATRIA $version";
		define("sistema_footer","SISTEMA AGROPATRIA  $version<br />© 2013  Todos los Derechos Reservados.");
		$versd=str_replace('<font color="red">NO VERSIONADO</font>','NO VERSIONADO',$version);
		define("sistema_title","SISTEMA AGROPATRIA   $versd");	
	
			$this->set('_a',false);
			$this->set('_b',$sistema_nombre);
			$this->set('_c',false);
			$this->set('_d',false);
			$this->set('_e',false);
			$this->set('_f',false);

		$this->layout="login";
		$usuario_id=$this->Session->read('usuario_id');
 		$users = $this->Session->read('usuario_id'); 

		if(isset($this->data['imagen'])){

		if(isset($usuario_id) && $usuario_id !='' && $usuario_id !=1)
		{  
		    //['conectado']='0'; desconectado
		    //['conectado']='1'; conectado
		    //['conectado']='2'; bloqueo la clave
		    //['conectado']='3'; bloqueado por el administrador
		

		   	$usuario_id = base64_decode(base64_decode(base64_decode(base64_decode(base64_decode($usuario_id)))));

		    $qry="update usuarios set conectado=0 where id=$usuario_id";
		    $this->Usuario->query($qry);
		}
		$this->Session->delete('usuario_id');$this->Session->destroy('usuario_id');
		$this->Session->delete('sesion_id');$this->Session->destroy('sesion_id');
		$this->Session->delete('nombre_usuario');$this->Session->destroy('nombre_usuario');
		$this->Session->delete('username');$this->Session->destroy('username');
		$this->Session->delete('Autenticado');$this->Session->destroy('Autenticado');
		$this->Session->delete('tienda_id');$this->Session->destroy('tienda_id');
		$this->Session->delete('nombre_tienda');$this->Session->destroy('nombre_tienda');
		$this->Session->delete('es_central');$this->Session->destroy('es_central');
		$this->Session->delete('cedula_usuario');$this->Session->destroy('cedula_usuario');
		$this->Session->delete('tlf_usuario');$this->Session->destroy('tlf_usuario');
		$this->Session->destroy();
		if(!empty($data['usuario']))$set_usuario=$data['usuario']; else $set_usuario='';
		if(!empty($data['clave']))$set_clave=$data['clave']; else $set_clave='';
		if(!empty($data['codigo']))$set_codigo=strtr(strtoupper($data['codigo']),"àèìòùáéíóúçñäëïöü","ÀÈÌÒÙÁÉÍÓÚÇÑÄËÏÖÜ");  else $set_codigo='';
		if(!empty($data['imagen']))$set_imagen=strtr(strtoupper($data['imagen']),"àèìòùáéíóúçñäëïöü","ÀÈÌÒÙÁÉÍÓÚÇÑÄËÏÖÜ"); else $set_imagen='';
		$set_mensaje='';
		

		if(empty($data['usuario']) or empty($data['clave']) /*or empty($data['codigo'])*/){ 
		
			if(empty($data['usuario']) and empty($data['clave'])){
				$set_mensaje='Existen Campos Vacios';
				$error=true;
				$set_usuario='';
				$set_clave='';		
				$set_codigo='';
			}
			else if(empty($data['usuario'])){
				if(empty($data['usuario'])){
					$error=true;
					$set_usuario=$data['usuario'];
					$set_mensaje='Indique un Usuario';
				}else $set_usuario='';
			}
			else if(empty($data['clave'])){
				if(empty($data['clave'])){
					$error=true;
					$set_clave=$data['clave'];
					$set_mensaje='Indique una Clave';
				}else $set_clave='';
			}
			else if(empty($data['codigo'])){
				if(empty($data['codigo'])){
					$error=true;
					$set_codigo=$data['codigo'];
					$set_mensaje='Indique el Codigo';
				}else   $set_codigo='';
			}
			else if(empty($data['imagen'])){
				if(empty($data['imagen'])){
					$error=true;
					$set_codigo=$data['codigo'];
					$set_mensaje='Error en Captcha';
				}
			}
			$this->set('_a',$error);
			$this->set('_c',$set_mensaje); 
			$this->set('_d',$set_usuario);
			$this->set('_e',$set_clave);
			$this->set('_f',$set_codigo);

		}
		else if($set_imagen!=$set_codigo){
			$this->set('_a',true);
			$this->set('_c',' El Codigo es Invalido');
			//$this->set('_c',' El Codigo "'.strtr(strtoupper($data['codigo']),"àèìòùáéíóúçñäëïöü","ÀÈÌÒÙÁÉÍÓÚÇÑÄËÏÖÜ").'" es Invalido');
			$this->set('_d',$data['usuario']);
			$this->set('_e',$data['clave']);
			$this->set('_f',$data['codigo']);
		}

		else
		{
			
			$usuario=trim(addslashes(strtr(strtoupper($data['usuario']), "àèìòùáéíóúçñäëïöü", "ÀÈÌÒÙÁÉÍÓÚÇÑÄËÏÖÜ")));
			$contrasena=trim(addslashes(md5($data['clave'])));
			$datosUsuario=$this->Usuario->find('first',array('conditions'=> array("UPPER(Usuario.usuario)='".$usuario."' AND Usuario.contrasena='".$contrasena."' and Usuario.estatus='1'")));



			if(count($datosUsuario)<1){
			$this->set('_a',false);
			$this->set('_c',' Error en Usuario o Clave');
			$this->set('_d',$data['usuario']);
			$this->set('_e',$data['clave']);
			$this->set('_f',$data['codigo']);

			}
			else{
				$id_usuario = $datosUsuario['Usuario']['id'];
				$id_usuario = base64_encode($id_usuario);
				$id_usuario = base64_encode($id_usuario);
				$id_usuario = base64_encode($id_usuario);
				$id_usuario = base64_encode($id_usuario);
				$id_usuario = base64_encode($id_usuario);
				$this->Session->write('usuario_id',$id_usuario);
				$tipo_usuario = $datosUsuario['Usuario']['tipo_usuario_id'];
				$tipo_usuario = base64_encode($tipo_usuario);
				$tipo_usuario = base64_encode($tipo_usuario);
				$tipo_usuario = base64_encode($tipo_usuario);
				$tipo_usuario = base64_encode($tipo_usuario);
				$tipo_usuario = base64_encode($tipo_usuario);
				$this->Session->write('tipo_usuario',$tipo_usuario);
				$this->Session->write('sesion_id',$this->Session->id());
				$this->Session->write('nombre_usuario',$datosUsuario['Funcionario']['nombre'].' '.$datosUsuario['Funcionario']['apellido']);
				$this->Session->write('cedula_usuario',$datosUsuario['Funcionario']['cedula']);
				$this->Session->write('tlf_usuario',$datosUsuario['Funcionario']['celular']);
				$this->Session->write('username',$datosUsuario['Usuario']['usuario']);
				$this->Session->write('hora_acceso',date('h:i:s'));
				$this->Session->write('Autenticado','Autenticado');
				$id_tienda = $datosUsuario['Usuario']['tienda_id'];
				$id_tienda = base64_encode($id_tienda);
				$id_tienda = base64_encode($id_tienda);
				$id_tienda = base64_encode($id_tienda);
				$id_tienda = base64_encode($id_tienda);
				$id_tienda = base64_encode($id_tienda);
				$this->Session->write('tienda_id',$id_tienda);
				$this->Session->write('nombre_tienda',$datosUsuario['Tienda']['nombre']);
				$this->Session->write('es_central',$datosUsuario['Tienda']['central']);
				
				$this->Session->write('passwordnube',base64_encode(base64_encode($data['clave'])));

				$this->request->data=null;
				$this->request->data['Usuario']['id']=$datosUsuario['Usuario']['id'];
				$this->request->data['Usuario']['conectado']='1';
				$this->request->data['Usuario']['session']=$this->Session->id(); 
					
	 			if ($this->Usuario->save($this->request->data))
	 			{
					//
					//$this->log('imprimir');
					$this->log();
					$this->request->data=null;

					$this->redirect('/'.$contr);
		  	}
				else
				{
				  	$this->set('_a',true);					
						$this->set('_c','Ocurrio un error inetente nuevamente');
		    }
	    }

		}
			

}else{
echo '';

}
	$this->set('_b',$sistema_nombre);		
		






}

	public function _logeo_salir() 
	{

		$this->layout="login";
	    $fun=$this->Session->read('usuario_id');
	    if($fun  && $fun !='' )
	    {
				 	$fun = base64_decode(base64_decode(base64_decode(base64_decode(base64_decode($fun)))));
	       	$qry="update usuarios set conectado=0 where id=$fun";
	        $this->Usuario->query($qry);
	    }
		
		$this->Session->delete('Autenticado');
		$this->Session->delete('tipo_usuario');
		$this->Session->delete('usuario_id');
		$this->Session->delete('user');
		$this->Session->delete('sesion_id');
		$this->Session->delete('tienda_id');
		$this->Session->delete('nombre_tienda');
		$this->Session->delete('es_central');
		$this->Session->delete('cedula_usuario');
		$this->Session->delete('tlf_usuario');
		$this->Session->delete('hora_acceso');
		$this->Session->destroy();
	  $this->redirect(SEG_SERVER);

	}

	function _logeo_index2() 
	{

		if($_POST){


		$data=$this->request->data;

		if(isset($_POST)/*and count($_POST)>1*/){


//		echo 'a controller';
/*
		echo '<pre>';
		print_r($data);
		echo '</pre>';
*/
	//	echo $_POST['nombre_usuario'];



		if(!isset($_POST['usuario_id']))$_POST['usuario_id']='';
		if(!isset($_POST['sistema_id']))$_POST['sistema_id']='';
		if(!isset($_POST['tipo_usuario']))$_POST['tipo_usuario']='';
		if(!isset($_POST['sesion_id']))$_POST['sesion_id']='';
		if(!isset($_POST['nombre_usuario']))$_POST['nombre_usuario']='';
		if(!isset($_POST['cedula_usuario']))$_POST['cedula_usuario']='';
		if(!isset($_POST['tlf_usuario']))$_POST['tlf_usuario']='';
		if(!isset($_POST['username']))$_POST['username']='';
		if(!isset($_POST['hora_acceso']))$_POST['hora_acceso']='';
		if(!isset($_POST['Autenticado']))$_POST['Autenticado']='';
		if(!isset($_POST['tienda_id']))$_POST['tienda_id']='';
		if(!isset($_POST['nombre_tienda']))$_POST['nombre_tienda']='';
		if(!isset($_POST['es_central']))$_POST['es_central']='';
		if(!isset($_POST['Config_userAgent']))$_POST['Config_userAgent']='';
		if(!isset($_POST['Config_time']))$_POST['Config_time']='';
		if(!isset($_POST['Config_countdown']))$_POST['Config_countdown']='';
		if(!isset($_POST['x']))$_POST['x']='';
		if(!isset($_POST['y']))$_POST['y']='';


		$this->Session->write('usuario_id',$_POST['usuario_id']);
		$this->Session->write('sistema_id',$_POST['sistema_id']);
		$this->Session->write('tipo_usuario',$_POST['tipo_usuario']);
		$this->Session->write('sesion_id',$_POST['sesion_id']);
		$this->Session->write('nombre_usuario',$_POST['nombre_usuario']);
		$this->Session->write('cedula_usuario',$_POST['cedula_usuario']);
		$this->Session->write('tlf_usuario',$_POST['tlf_usuario']);
		$this->Session->write('username',$_POST['username']);
		$this->Session->write('hora_acceso',$_POST['hora_acceso']);
		$this->Session->write('Autenticado',$_POST['Autenticado']);
		$this->Session->write('tienda_id',$_POST['tienda_id']);
		$this->Session->write('nombre_tienda',$_POST['nombre_tienda']);
		$this->Session->write('es_central',$_POST['es_central']);
		$this->Session->write('userAgent',$_POST['Config_userAgent']);
		$this->Session->write('time',$_POST['Config_time']);
		$this->Session->write('countdown',$_POST['Config_countdown']);
		$this->Session->write('x',$_POST['x']);
		$this->Session->write('y',$_POST['y']);




		//$this->Session->write('tipo',$_POST['nombre']);

							$this->redirect('/'.PRINCIPAL);
		}else{
							$this->redirect('/'.PRINCIPAL.'/index');
		}

		}
		else{
		 echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.servidor.'">';
		}

}

function _logeo_index2_ventas() 
{
	if($_POST){
		$data=$this->request->data;
		if(isset($_POST))
		{
			if(!isset($_POST['usuario_id']))$_POST['usuario_id']='';
			if(!isset($_POST['sistema_id']))$_POST['sistema_id']='';
			if(!isset($_POST['tipo_usuario']))$_POST['tipo_usuario']='';
			if(!isset($_POST['sesion_id']))$_POST['sesion_id']='';
			if(!isset($_POST['nombre_usuario']))$_POST['nombre_usuario']='';
			if(!isset($_POST['cedula_usuario']))$_POST['cedula_usuario']='';
			if(!isset($_POST['tlf_usuario']))$_POST['tlf_usuario']='';
			if(!isset($_POST['username']))$_POST['username']='';
			if(!isset($_POST['hora_acceso']))$_POST['hora_acceso']='';
			if(!isset($_POST['Autenticado']))$_POST['Autenticado']='';
			if(!isset($_POST['tienda_id']))$_POST['tienda_id']='';
			if(!isset($_POST['nombre_tienda']))$_POST['nombre_tienda']='';
			if(!isset($_POST['es_central']))$_POST['es_central']='';
			if(!isset($_POST['Config_userAgent']))$_POST['Config_userAgent']='';
			if(!isset($_POST['Config_time']))$_POST['Config_time']='';
			if(!isset($_POST['Config_countdown']))$_POST['Config_countdown']='';
			if(!isset($_POST['x']))$_POST['x']='';
			if(!isset($_POST['y']))$_POST['y']='';

			$this->Session->write('usuario_id',$_POST['usuario_id']);
			$this->Session->write('sistema_id',$_POST['sistema_id']);
			$this->Session->write('tipo_usuario',$_POST['tipo_usuario']);
			$this->Session->write('sesion_id',$_POST['sesion_id']);
			$this->Session->write('nombre_usuario',$_POST['nombre_usuario']);
			$this->Session->write('cedula_usuario',$_POST['cedula_usuario']);
			$this->Session->write('tlf_usuario',$_POST['tlf_usuario']);
			$this->Session->write('username',$_POST['username']);
			$this->Session->write('hora_acceso',$_POST['hora_acceso']);
			$this->Session->write('Autenticado',$_POST['Autenticado']);
			$this->Session->write('tienda_id',$_POST['tienda_id']);
			$this->Session->write('nombre_tienda',$_POST['nombre_tienda']);
			$this->Session->write('es_central',$_POST['es_central']);
			$this->Session->write('userAgent',$_POST['Config_userAgent']);
			$this->Session->write('time',$_POST['Config_time']);
			$this->Session->write('countdown',$_POST['Config_countdown']);
			$this->Session->write('x',$_POST['x']);
			$this->Session->write('y',$_POST['y']);
			$this->redirect('/PuntoVentas');
		}
		else
		{
			$this->redirect('/PuntoVentas/index');
		}
	}
	else{
		 echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.servidor.'">';
	}
}


	public function _logeo_nlogin() 
	{
	//	$this->Vista->tsesion(1);
	//	$this->Vista->title('Sesion Cerrada');


//		$this->render('../Login/nlogin');
//		return false;
	}

	public function _logeo_relogeo() 
	{
echo 'sssssssss';
echo "<script type='text/javascript'>
alert('aqui');
</script>";

  }


	public function sesion() {

	//	$this->layout="login";
	 $data=$this->request->data;
		if(!isset($data['usuario_id'])){
  		 echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.servidor.'">';
		}
    else if(empty($data['usuario']) or $data['usuario']==''){
			$this->set('error_entrada',true);
			$this->Vista->mensaje(' Indique un Usuario','ERROR');	
			$this->set('usuario',$data['usuario']);
			$this->set('clave',$data['clave']);
			$this->set('anterior_codigo',$data['codigo']);
			$this->set('imagen',$data['imagen']);
		}
    else if(empty($data['clave']) or $data['clave']==''){
			$this->set('error_entrada',true);
			$this->Vista->mensaje(' Indique una Clave','ERROR');	
			$this->set('usuario',$data['usuario']);
			$this->set('clave',$data['clave']);
			$this->set('anterior_codigo',$data['codigo']);
			$this->set('imagen',$data['imagen']);
		}	
    else if(empty($data['codigo']) or $data['codigo']==''){
			$this->set('error_entrada',true);
			$this->Vista->mensaje(' Indique el Codigo de Validación','ERROR');	
			$this->set('usuario',$data['usuario']);
			$this->set('clave',$data['clave']);
			$this->set('anterior_codigo',$data['codigo']);
			$this->set('imagen',$data['imagen']);
		}
    else if($data['imagen']!=$this->Utilitario->mayuscula($data['codigo'])){
			$this->set('error_entrada',true);
			$this->Vista->mensaje(' El Codigo es Invalido','ERROR');	
			$this->set('usuario',$data['usuario']);
			$this->set('clave',$data['clave']);
			$this->set('anterior_codigo',$data['codigo']);
		}
		else{

			if(isset($data['usuario_id'])){

	    		$usuario_id_c= $data['usuario_id'];
//"VmtaYVJrOVdRbEpRVkRBOQ==";//base64_encode(base64_encode(base64_encode(base64_encode(base64_encode($data['usuario_id'])))));
		  		$usuario_id = base64_decode(base64_decode(base64_decode(base64_decode(base64_decode($usuario_id_c)))));
      			$usuario=$this->Utilitario->mayuscula($data['usuario']);
		  		$contrasena=$this->Utilitario->con_clave($data['clave']);
				$datosUsuario=$this->Usuario->find('first',array('conditions'=> array("UPPER(Usuario.usuario)='".$usuario."'AND Usuario.contrasena='".$contrasena."' and Usuario.id='$usuario_id' and Usuario.estatus='1'")));

			if(count($datosUsuario)<1){
			$this->set('error_entrada',false);
			$this->Vista->mensaje(' Error en Usuario o Clave ','ERROR');	
			$this->set('usuario',$data['usuario']);
			$this->set('clave',$data['clave']);
			$this->set('anterior_codigo',$data['codigo']);
			}
			else{
$this->_sesion_plana('php');
$this->_sesion_plana('plana');



$ventana=$data['ventana'];

echo "<script type='text/javascript'>
document.getElementById('buscadorindex').value='';
document.getElementById('buscadorindex').disabled = false;
</script>";

					$this->request->data=null;	
				echo "<script type='text/javascript'>
					  var h = Ext.getCmp('$ventana');
	          h.show ? h.hide() : h.hide();
						h = null;
						$ventana=null;
      				</script>";
				$this->Vista->tsesion(0);
			  $this->Vista->title('Sesion Activada');
			}

			}
      else{
  		 echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.servidor.'">';
      }

    }


  }


	function validar()
	{
    //echo "<script type='text/javascript'>alert('funcion validar');</script>";
		if($this->Session->read('Autenticado')==false){ 
			/////AUTOMATICO BY JERV&&DJAP//////////
			$this->_sesion_plana('php');
			$this->_sesion_plana('plana');
			if($this->Session->read('Autenticado')==false){
				$this->Vista->tsesion(1);
				$this->Vista->title('Sesion Cerrada');
				echo "<script type='text/javascript'>
			  document.getElementById('buscadorindex').value='BLOQUEADO';
				document.getElementById('buscadorindex').disabled = true;
				      </script>";	 
		      $this->render('../'.LOGIN.'/nlogin');
		      return 0;
			}
			/////////////
////////////////VALIDAR SESSION DE JUAN//////////////////////////////////////

	/*
		$this->Vista->tsesion(1);
		$this->Vista->title('Sesion Cerrada');

		echo "<script type='text/javascript'>
	  document.getElementById('buscadorindex').value='BLOQUEADO';
		document.getElementById('buscadorindex').disabled = true;
		      </script>";	 
      $this->render('../'.LOGIN.'/nlogin');
      return 0;
      */

    }
    return 1;

  }





function log ($imprimir=null){

if($imprimir=='ver' or $imprimir===1){
$mk=MKTIME;
echo '<div id="session'.$mk.'" style="display:block;" class="x-hide-display">';
$this->log_session();
echo '</div>';

echo '<div id="query'.$mk.'" style="display:block;" class="x-hide-display">';
$this->log_sql();
echo '</div>';

echo '<div id="reques'.$mk.'" style="display:block;" class="x-hide-display">';
$this->log_server();
echo'</div>';

echo '<div id="cookis'.$mk.'" style="display:block;" class="x-hide-display">';
$this->log_cookis();
echo '</div>';

echo '<div id="post'.$mk.'" style="display:block;" class="x-hide-display">';
$this->log_post();
echo '</div>';

echo '<div id="get'.$mk.'" style="display:block;" class="x-hide-display">';
$this->log_get();
echo '</div>';



echo"<script type='text/javascript'>
document.getElementById('ayudadiv').style.display='block';
document.getElementById('ayudadiv').innerHTML='&nbsp';
document.getElementById('ayudabottomdiv').style.display='block';
document.getElementById('ayudabottomdiv').innerHTML='&nbsp';
//document.getElementById('ayudabottomdiv').innerHTML='<br><br><br><br><br><br><br><br><br><br><br>';

Ext.onReady(function(){
    var win,
            win = Ext.create('widget.window', {
                title: 'Ayuda de Desarrollo',
                closable: true,
								iconCls: 'information',
                closeAction: 'hide',
                width: '80%',
                minWidth: 30,
                height: '80%',
                layout: 'border',
								maximizable: true,
								modal: true,
                bodyStyle: 'padding: 5px;',
                items: [{
                    region: 'center',
                    xtype: 'tabpanel',
                    items: [
{ title: 'SENTENCIAS SQL',autoScroll: true,closable: true,contentEl: 'query".$mk."'},
{ title: 'VARIABLES SESSION',autoScroll: true,closable: true,contentEl: 'session".$mk."'},
{ title: 'METHOD REQUEST',autoScroll: true,closable: true,contentEl: 'reques".$mk."'},
{ title: 'COOKIS',autoScroll: true,closable: true,contentEl: 'cookis".$mk."'},
{ title: 'METHOD POST',autoScroll: true,closable: true,contentEl: 'post".$mk."'},
{ title: 'METHOD GET',autoScroll: true,closable: true,contentEl: 'get".$mk."'}
]
                }]
            });
		win.show();
});
</script>";
}
else{
/////////////////////

/*if (!class_exists('ConnectionManager') || Configure::read('debug') < 2) {
	return false;
}*/


$noLogs = !isset($logs);
if ($noLogs):
	$sources = ConnectionManager::sourceList();

	$logs = array();
	foreach ($sources as $source):
		$db = ConnectionManager::getDataSource($source);
		if (!method_exists($db, 'getLog')):
			continue;
		endif;
		$logs[$source] = $db->getLog();
	endforeach;
endif;

if ($noLogs || isset($_forced_from_dbo_)):

	foreach ($logs as $source => $logInfo):
		$text = $logInfo['count'] > 1 ? 'queries' : 'query';

$transaccion=date('dmyhis').mktime(date("s"));

$fecha=date('Y-m-d h:i:s');//2012-02-23 11:49:10.809611

		foreach ($logInfo['log'] as $k => $i) :
			$i += array('error' => '');
			if (!empty($i['params']) && is_array($i['params'])) {
				$bindParam = $bindType = null;
				if (preg_match('/.+ :.+/', $i['query'])) {
					$bindType = true;
				}
				foreach ($i['params'] as $bindKey => $bindVal) {
					if ($bindType === true) {
						$bindParam .= h($bindKey) ." => " . h($bindVal) . ", ";
					} else {
						$bindParam .= h($bindVal) . ", ";
					}
				}
				$i['query'] .= " , params[ " . rtrim($bindParam, ', ') . " ]";
			}

$query=$i['query'];
$query=str_replace("'","\comilla/",$query);
$qry="INSERT INTO logsqls (usuario, ip,transaccion,nr,query,error,afectada,num_rows,took_ms,fecha)
VALUES('".$this->Session->read('username')."', '".$_SERVER['REMOTE_ADDR']."', '".$transaccion."', ".($k + 1).", '".$query."', '{$i['error']}', '{$i['affected']}', '{$i['numRows']}', '{$i['took']}', '$fecha');";

		   
                    $this->Logsql = ClassRegistry::init('Logsql');
		    $this->Logsql->query($qry);



		endforeach;



	?>

	<?php
	endforeach;
else:
	echo '';
endif;



/////////////////////
}


}


///////////////////////////////////////////////////////////////


function log_post(){

$valor="<br />
<table border='1' cellpadding='0' cellspacing='0' width='95%' align='center' style='border:10;'>";
$valor.="<tr bgcolor='#CCCCCC'><td align='right' width='100px'><b>VARIABLE&nbsp;&nbsp;</b></td><td align='left'>&nbsp;&nbsp;<b>VALOR</b></td></tr>";
foreach ($_POST as $key => $value){
$valor.="<tr><td align='right' width='100px'><b>$key&nbsp;&nbsp;</b></td><td align='left'>&nbsp;&nbsp;".trim($value)."</td></tr>";
}
$valor.="</table>";
echo $valor;
}

function log_get(){
$valor="<br />
<table border='1' cellpadding='0' cellspacing='0' width='95%' align='center' style='border:10;'>";
$valor.="<tr bgcolor='#CCCCCC'><td align='right' width='100px'><b>VARIABLE&nbsp;&nbsp;</b></td><td align='left'>&nbsp;&nbsp;<b>VALOR</b></td></tr>";
foreach ($_GET as $key => $value){
$valor.="<tr><td align='right' width='100px'><b>$key&nbsp;&nbsp;</b></td><td align='left'>&nbsp;&nbsp;".trim($value)."</td></tr>";
}
$valor.="</table>";
echo $valor;
}

function log_server(){
$valor="<br />
<table border='1' cellpadding='0' cellspacing='0' width='95%' align='center' style='border:10;'>";
$valor.="<tr bgcolor='#CCCCCC'><td align='right' width='100px'><b>VARIABLE&nbsp;&nbsp;</b></td><td align='left'>&nbsp;&nbsp;<b>VALOR</b></td></tr>";
foreach ($_SERVER as $key => $value){
if($key!='HTTP_COOKIE'){
$valor.="<tr><td align='right' width='100px'><b>$key&nbsp;&nbsp;</b></td><td align='left'>&nbsp;&nbsp;".trim($value)."</td></tr>";
}
}
$valor.="</table>";
echo $valor;
}

function log_cookis(){
$valor="<br />
<table border='1' cellpadding='0' cellspacing='0' width='95%' align='center' style='border:10;'>";
$valor.="<tr bgcolor='#CCCCCC'><td align='right' width='100px'><b>VARIABLE&nbsp;&nbsp;</b></td><td align='left'>&nbsp;&nbsp;<b>VALOR</b></td></tr>";
$server=explode(';',$_SERVER['HTTP_COOKIE']);
for($i=0; $i<count($server); $i++){
$sd=explode('=',$server[$i]);
if($sd[1]=='+')$sd[1]='<font color="red">varible limpiada por View.php PADRE </font>';
$valor.="<tr><td align='right' width='100px'><b>".$sd[0]."&nbsp;&nbsp;</b></td><td align='left'>&nbsp;&nbsp;".trim($sd[1])."</td></tr>";
}
$valor.="</table>";
echo $valor;
}



function log_sql(){

$XXX=MKTIME;
$valor="";
if (!class_exists('ConnectionManager') || Configure::read('debug') < 2) {
	return false;
}
$noLogs = !isset($logs);
if ($noLogs):
	$sources = ConnectionManager::sourceList();
	$logs = array();
	foreach ($sources as $source):
		$db = ConnectionManager::getDataSource($source);
		if (!method_exists($db, 'getLog')):
			continue;
		endif;
		$logs[$source] = $db->getLog();
	endforeach;
endif;

if ($noLogs || isset($_forced_from_dbo_)):

	foreach ($logs as $source => $logInfo):
		$text = $logInfo['count'] > 1 ? 'queries' : 'query';

	?>

	<?php
$transaccion=date('dmyhis').mktime(date("s"));

$fecha=date('Y-m-d h:i:s');//2012-02-23 11:49:10.809611



$valor.="
<br /><br />
<table border='0' cellpadding='0' cellspacing='0' width='95%' align='center' style='border:10;'>
<tr>
<td align='left'>
<table border='1' cellpadding='0' cellspacing='0' align='left' style='border:10;'>
<tr bgcolor='#cccccc' align='center' style='cursor:pointer;'>
<td width='auto' align='left'><b><font color='#545454' size='-2' title='DATO'>&nbsp;DATO</font></b></td>
<td width='auto' align='left'><b><font color='#545454' size='-2' title='VALOR'>&nbsp;VALOR</font></b></td>
</tr>


<tr bgcolor='#ffffff' align='left' style='cursor:pointer;'>
<td width='auto'><b><font color='#545454' size='-2' title='FECHA'>&nbsp;FECHA:</font></b></td>
<td width='auto' align='left'><b><font color='#545454' size='-2' title='$fecha'>&nbsp;$fecha</font></b></td>
</tr>
<tr bgcolor='#ffffff' align='left' style='cursor:pointer;'>
<td width='auto'><b><font color='#545454' size='-2' title='USUARIO'>&nbsp;USUARIO:</font></b></td>
<td width='auto' align='left'><b><font color='#545454' size='-2' title='".$this->Session->read('username')."'>&nbsp;".$this->Session->read('username')."</font></b></td>
</tr>
<tr bgcolor='#ffffff' align='left' style='cursor:pointer;'>
<td width='auto'><b><font color='#545454' size='-2' title='DIRECCION IP'>&nbsp;DIRECCION IP:</font></b></td>
<td width='auto' align='left'><b><font color='#545454' size='-2' title=''".$_SERVER['REMOTE_ADDR']."'>&nbsp;'".$_SERVER['REMOTE_ADDR']."</font></b></td>
</tr>
<tr bgcolor='#ffffff' align='left' style='cursor:pointer;'>
<td width='auto'><b><font color='#545454' size='-2' title='TRANSACCION'>&nbsp;TRANSACCION:</font></b></td>
<td width='auto' align='left'><b><font color='#545454' size='-2' title='".$transaccion."'>&nbsp;".$transaccion."</font></b></td>
</tr>
</table>
</td>
</tr>
<tr><td align='left'>
<br />
<table border='1' cellpadding='0' cellspacing='0' width='100%' align='center' style='border:10;'>
<tr bgcolor='#cccccc' align='center' style='cursor:pointer;'>
<td width='auto'><b><font color='#545454' size='-2' title='NR'>&nbsp;NR</font></b></td>
<td width='auto'><b><font color='#545454' size='-2' title='QUERY'>&nbsp;QUERY</font></b></td>
<td width='auto'><b><font color='#545454' size='-2' title='ERROR'>&nbsp;ERROR</font></b></td>
<td width='auto'><b><font color='#545454' size='-2' title='T.AFECTADA'>&nbsp;T.AFECTADA</font></b></td>
<td width='auto'><b><font color='#545454' size='-2' title='NUM_ROWS'>&nbsp;NUM_ROWS</font></b></td>
<td width='auto'><b><font color='#545454' size='-2' title='TOOK_MS'>&nbsp;TOOK_MS</font></b></td>

</tr>
";

		foreach ($logInfo['log'] as $k => $i) :
			$i += array('error' => '');
			if (!empty($i['params']) && is_array($i['params'])) {
				$bindParam = $bindType = null;
				if (preg_match('/.+ :.+/', $i['query'])) {
					$bindType = true;
				}
				foreach ($i['params'] as $bindKey => $bindVal) {
					if ($bindType === true) {
						$bindParam .= h($bindKey) ." => " . h($bindVal) . ", ";
					} else {
						$bindParam .= h($bindVal) . ", ";
					}
				}
				$i['query'] .= " , params[ " . rtrim($bindParam, ', ') . " ]";
			}
/*
if($imp!='ver' or $imprimir!=1){
$query=$i['query'];
$query=str_replace("'","\comilla/",$query);
$qry="INSERT INTO logsqls (usuario, ip,transaccion,nr,query,error,afectada,num_rows,took_ms,fecha)
VALUES('".$this->Session->read('username')."', '".$_SERVER['REMOTE_ADDR']."', '".$transaccion."', ".($k + 1).", '".$query."', '{$i['error']}', '{$i['affected']}', '{$i['numRows']}', '{$i['took']}', '$fecha');";

		   
                    $this->Logsql = ClassRegistry::init('Logsql');
		    $this->Logsql->query($qry);

}
*/

if (($k + 1) % 2 == 0) $class = "#FFFFFF"; else $class = "#F0F0F0";
$valor.="
<tr bgcolor='$class' align='left' style='cursor:pointer;'>
<td width='auto' align='center'><b><font color='#545454' size='-2' title='nr'>" . ($k + 1) . "</font></b></td>
<td width='auto' align='left'><b><font color='#545454' size='-2' title='" . h($i['query']) . "'>&nbsp;" . h($i['query']) . "</font></b></td>
<td width='auto' align='center'><b><font color='#545454' size='-2' title='{$i['error']}'>&nbsp;{$i['error']}</font></b></td>
<td width='auto' align='center'><b><font color='#545454' size='-2' title='{$i['affected']}'>{$i['affected']}</font></b></td>
<td width='auto' align='center'><b><font color='#545454' size='-2' title='{$i['numRows']}'>{$i['numRows']}</font></b></td>
<td width='auto' align='center'><b><font color='#545454' size='-2' title='{$i['took']}'>{$i['took']}</font></b></td>
</tr>
";

		endforeach;

$valor.="</table></td></tr></table>";

	?>

	<?php
	endforeach;
else:
	echo '';
endif;


//if($imp=='ver' or $imp===1){
echo $valor;
//}
}


function log_session(){
$valor="
<br />
<table border='1' cellpadding='0' cellspacing='0' width='95%' align='center' style='border:10;'>";


$valor.="<tr bgcolor='#CCCCCC'><td align='right' width='100px'><b>VARIABLE&nbsp;&nbsp;</b></td><td align='left'>&nbsp;&nbsp;<b>VALOR</b></td></tr>";
foreach ($_SESSION as $key => $value){
if($key!='Config'){
$valor.="<tr><td align='right' width='100px'><b>$key&nbsp;&nbsp;</b></td><td align='left'>&nbsp;&nbsp;$value</td></tr>";
}
}

$valor.="<tr bgcolor='#CCCCCC'><td align='right' width='100px'><b>VARIABLE CAKEPHP&nbsp;&nbsp;</b></td><td align='left'>&nbsp;&nbsp;<b>VALOR -> Tomados de \" ".'$_SESSION[\'Config\']'." \"</b></td></tr>";
foreach ($_SESSION['Config'] as $key => $value){
$valor.="<tr><td align='right' width='100px'><b>$key&nbsp;&nbsp;</b></td><td align='left'>&nbsp;&nbsp;$value</td></tr>";
}
$valor.="</table>";
echo $valor;

}




///////////////////////////////////////////////////////////////


function log2($imp='vacio'){

$XXX=mktime(date('his'));
$valor="";
if (!class_exists('ConnectionManager') || Configure::read('debug') < 2) {
	return false;
}
$noLogs = !isset($logs);
if ($noLogs):
	$sources = ConnectionManager::sourceList();

	$logs = array();
	foreach ($sources as $source):
		$db = ConnectionManager::getDataSource($source);
		if (!method_exists($db, 'getLog')):
			continue;
		endif;
		$logs[$source] = $db->getLog();
	endforeach;
endif;

if ($noLogs || isset($_forced_from_dbo_)):

	foreach ($logs as $source => $logInfo):
		$text = $logInfo['count'] > 1 ? 'queries' : 'query';

	?>

	<?php
$transaccion=date('dmyhis').mktime(date("s"));

$fecha=date('Y-m-d h:i:s');//2012-02-23 11:49:10.809611



$valor.="
<div id='".$XXX."' class='x-hide-display'>
<br /><br />
<table border='0' cellpadding='0' cellspacing='0' width='95%' align='center' style='border:10;'>
<tr>
<td align='left'>
<table border='1' cellpadding='0' cellspacing='0' align='left' style='border:10;'>
<tr bgcolor='#cccccc' align='center' style='cursor:pointer;'>
<td width='auto' align='left'><b><font color='#545454' size='-2' title='DATO'>&nbsp;DATO</font></b></td>
<td width='auto' align='left'><b><font color='#545454' size='-2' title='VALOR'>&nbsp;VALOR</font></b></td>
</tr>


<tr bgcolor='#ffffff' align='left' style='cursor:pointer;'>
<td width='auto'><b><font color='#545454' size='-2' title='FECHA'>&nbsp;FECHA:</font></b></td>
<td width='auto' align='left'><b><font color='#545454' size='-2' title='$fecha'>&nbsp;$fecha</font></b></td>
</tr>
<tr bgcolor='#ffffff' align='left' style='cursor:pointer;'>
<td width='auto'><b><font color='#545454' size='-2' title='USUARIO'>&nbsp;USUARIO:</font></b></td>
<td width='auto' align='left'><b><font color='#545454' size='-2' title='".$this->Session->read('username')."'>&nbsp;".$this->Session->read('username')."</font></b></td>
</tr>
<tr bgcolor='#ffffff' align='left' style='cursor:pointer;'>
<td width='auto'><b><font color='#545454' size='-2' title='DIRECCION IP'>&nbsp;DIRECCION IP:</font></b></td>
<td width='auto' align='left'><b><font color='#545454' size='-2' title=''".$_SERVER['REMOTE_ADDR']."'>&nbsp;'".$_SERVER['REMOTE_ADDR']."</font></b></td>
</tr>
<tr bgcolor='#ffffff' align='left' style='cursor:pointer;'>
<td width='auto'><b><font color='#545454' size='-2' title='TRANSACCION'>&nbsp;TRANSACCION:</font></b></td>
<td width='auto' align='left'><b><font color='#545454' size='-2' title='".$transaccion."'>&nbsp;".$transaccion."</font></b></td>
</tr>
</table>
</td>
</tr>
<tr><td align='left'>
<br />
<table border='1' cellpadding='0' cellspacing='0' width='100%' align='center' style='border:10;'>
<tr bgcolor='#cccccc' align='center' style='cursor:pointer;'>
<td width='auto'><b><font color='#545454' size='-2' title='NR'>&nbsp;NR</font></b></td>
<td width='auto'><b><font color='#545454' size='-2' title='QUERY'>&nbsp;QUERY</font></b></td>
<td width='auto'><b><font color='#545454' size='-2' title='ERROR'>&nbsp;ERROR</font></b></td>
<td width='auto'><b><font color='#545454' size='-2' title='T.AFECTADA'>&nbsp;T.AFECTADA</font></b></td>
<td width='auto'><b><font color='#545454' size='-2' title='NUM_ROWS'>&nbsp;NUM_ROWS</font></b></td>
<td width='auto'><b><font color='#545454' size='-2' title='TOOK_MS'>&nbsp;TOOK_MS</font></b></td>

</tr>
";

		foreach ($logInfo['log'] as $k => $i) :
			$i += array('error' => '');
			if (!empty($i['params']) && is_array($i['params'])) {
				$bindParam = $bindType = null;
				if (preg_match('/.+ :.+/', $i['query'])) {
					$bindType = true;
				}
				foreach ($i['params'] as $bindKey => $bindVal) {
					if ($bindType === true) {
						$bindParam .= h($bindKey) ." => " . h($bindVal) . ", ";
					} else {
						$bindParam .= h($bindVal) . ", ";
					}
				}
				$i['query'] .= " , params[ " . rtrim($bindParam, ', ') . " ]";
			}

if($imp!='imprimir' or !isset($imp)){
$query=$i['query'];
$query=str_replace("'","\comilla/",$query);
$qry="INSERT INTO logsqls (usuario, ip,transaccion,nr,query,error,afectada,num_rows,took_ms,fecha)
VALUES('".$this->Session->read('username')."', '".$_SERVER['REMOTE_ADDR']."', '".$transaccion."', ".($k + 1).", '".$query."', '{$i['error']}', '{$i['affected']}', '{$i['numRows']}', '{$i['took']}', '$fecha');";

		   
                    $this->Logsql = ClassRegistry::init('Logsql');
		    $this->Logsql->query($qry);

}


if (($k + 1) % 2 == 0) $class = "#FFFFFF"; else $class = "#F0F0F0";
$valor.="
<tr bgcolor='$class' align='left' style='cursor:pointer;'>
<td width='auto' align='center'><b><font color='#545454' size='-2' title='nr'>" . ($k + 1) . "</font></b></td>
<td width='auto' align='left'><b><font color='#545454' size='-2' title='" . h($i['query']) . "'>&nbsp;" . h($i['query']) . "</font></b></td>
<td width='auto' align='center'><b><font color='#545454' size='-2' title='{$i['error']}'>&nbsp;{$i['error']}</font></b></td>
<td width='auto' align='center'><b><font color='#545454' size='-2' title='{$i['affected']}'>{$i['affected']}</font></b></td>
<td width='auto' align='center'><b><font color='#545454' size='-2' title='{$i['numRows']}'>{$i['numRows']}</font></b></td>
<td width='auto' align='center'><b><font color='#545454' size='-2' title='{$i['took']}'>{$i['took']}</font></b></td>
</tr>
";

		endforeach;

$valor.="</table></td></tr></table></div>";

	?>

	<?php
	endforeach;
else:
	echo '';
endif;




$valor.="
<style type='text/css'>
.grid {

    background-image:url(img/iconos/icons/grid.png);
}
.folder_wrench {
    background-image:url(img/iconos/icons/folder_wrench.png);
}

.gogle {
    background-image:url(img/iconos/icons/gogle.png);
}
.plugin_add {
    background-image:url(img/iconos/icons/plugin_add.png);

}
.gogle_palena {
    background-image:url(img/iconos/icons/gogle_palena.png);
}
.book {

    background-image:url(img/iconos/icons/book.png);
}
.cross {
    background-image:url(img/iconos/icons/cross.gif);
}
.accept {
    background-image:url(img/iconos/icons/accept.png);
}



</style>

<script type='text/javascript'>

Ext.onReady(function() {
    var ventana ,
    ventana=Ext.create('Ext.window.Window', {
//        id : 'mensaje',
        title : 'CONSULTA SQL EJECUTADAS',
        layout: 'fit',
//	layout: 'border',
        width: '80%',
        height: '80%',
        minWidth: '30%',
	minHeight: '20%',
	layoutManagedWidth:2,
    	contentEl: '$XXX',
        maximizable: true,
	iconCls: 'grid',
	animateTarget: 'vista',
        collapsed: true,
        collapsible: true,
	constrain: true,
	modal: false,
	autoScroll: true,


	//closeAction: 'win',
		hideLabel: true,
		floatable: true,
		bodyStyle: 'padding: 5px;background-color:#FFFFFF;',

 		items: [],

    });
ventana.show();

});
</script>";


//$valor.="<script type='text/javascript'>document.getElementById('$XXX').style.display='block';</script>";

if($imp=='imprimir'){
echo $valor;
}

}

function _principal_buscador($model = null, $controler=null, $valor = null, $permi=null, $render=true) 
{
	$this->layout = 'ajax';
	if($model!='Inicio')
	{
		if($controler!='vacio')
		{
			$per_lis=explode('|',$permi);
			foreach ($per_lis as $llave => $valorpermi)
			{
				$per_aux=explode('=',$valorpermi);
				if(isset($per_aux[1])){ $this->set($per_aux[0],$per_aux[1]);}
			}
			if($controler!=null) $url=str_replace('xreplacex','/',$controler);
			if($valor=='' or $valor==null or $valor=='0')$valor='';
		
			$this->mode_buscador = ClassRegistry::init($model);
			$campos = $this->mode_buscador->query("SELECT column_name FROM information_schema.columns WHERE table_name = '" .$this->mode_buscador->useTable. "'");
			
			
			$todo='(';
			
			$modelos = $this->mode_buscador->relaccion;
		
			for($i=0; $i< count($modelos);$i++)
			{
				$camds='nombre'; 
				$m=$modelos[$i];
				$this->aux = ClassRegistry::init($m);
				if(isset($this->aux->buscador) and !empty($this->aux->buscador))	
					$camds=$this->aux->buscador; 
		      	$todo.='"CAST(' . $modelos[$i] . '.'.$camds.'' . ' AS VARCHAR(500))"' . " ilike '%" . $valor . "%' OR ";
			}
			for ($i = 0; $i < count($campos); $i++) 
			{
				if (in_array($campos[$i][0]['column_name'], $this->mode_buscador->busqueda)) 
				{
                	$todo.='"CAST(' . $model . '.' . $campos[$i][0]['column_name'] . ' AS VARCHAR(500))"' . " ilike '%" . $valor . "%' OR ";
                }
			} 
			$tod = substr($todo, 0, -3);
			
			if(isset($this->mode_buscador->estatus)) $tod.=") AND $model.{$this->mode_buscador->estatus} != 0";
			else $tod.=") AND $model.estatus !=0 ";


			$tipo_usuario=$this->Interfaz->id($this->Session->read('tipo_usuario'));
			$tienda_id=$this->Interfaz->id($this->Session->read('tienda_id'));
			if($tipo_usuario!=1 and $tipo_usuario!=3)
			{
				if(($model=='Productor' or $model=='Usuario' or $model=='Funcionario') && (sistema !='SUBSIDIOS AGROPATRIA'))
				{
					$tod.=' AND "'.$model.'.tienda_id"='.$tienda_id;
				}
			}
			$condicion = array("or" => array($tod));
			$ord_bus= (isset($this->mode_buscador->order) && !empty($this->mode_buscador->order)) ? $this->mode_buscador->order : "$model.id";
			if (!defined('PAGINADOR')) {  define('PAGINADOR', 1); }
			if(PAGINADOR==1){

			$total= $this->mode_buscador->find('count',array('conditions'=> $condicion));
            $data = $this->mode_buscador->find('all', array('conditions' => $condicion, 'order' => $ord_bus, 'limit'=>MAX_PAGI));
            if($total>MAX_PAGI) $mos=MAX_PAGI;
			else $mos=$total;
            $this->Vista->title('Listado de Registros Encontrados (Mostrando '.$mos.' de '.$total.' Registros Encontrados)');
        	}
        	else{
        		$na=$this->mode_buscador->name;
        		$data = $this->paginate('Producto', array($condicion));
        	}
			$this->set('data', $data);
			$this->set('busq', $valor);

			if($render==true)
			{
	  			if($controler!=null)
				{
					$da=explode('/',$url);
       				$this->render("../".$da[0]."/".$da[1]);
				}
			}
		}
		else
		{
			$this->Vista->mensaje('Primero debes seleccionar un links del menu','ALERTA');
			$this->render("../".PRINCIPAL."/imagen");
		}
	}
	else
	{
		$this->Vista->mensaje('El links Inicio no posee ni debe poseer busquedas','ALERTA');
		$this->render("../".PRINCIPAL."/imagen");
	}
}


function _principal_buscador_reporte($model = null, $valor = null) 
{
	if($model!='Inicio')
	{
		$this->mode_buscador = ClassRegistry::init($model);
		$ord_bus= (isset($this->mode_buscador->order) && !empty($this->mode_buscador->order)) ? $this->mode_buscador->order : "$model.id";
		if($valor=='' or $valor==null or $valor=='0'){
			if(isset($this->mode_buscador->estatus)) $condicion=array("$model.{$this->mode_buscador->estatus} != " => 0);
			else $condicion=array($model.".estatus != "=> 0);
			$data = $this->mode_buscador->find('all', array('conditions' => $condicion, 'order' => $ord_bus));
		}
		else{
			$modelos = $this->mode_buscador->relaccion;
			$campos = $this->mode_buscador->query("SELECT column_name FROM information_schema.columns WHERE table_name = '" .$this->mode_buscador->useTable. "'");
			$todo='(';
			
			for($i=0; $i< count($modelos);$i++)
			{
				$camds='nombre'; 
				$m=$modelos[$i];
				$this->aux = ClassRegistry::init($m);
				if(isset($this->aux->buscador) and !empty($this->aux->buscador))	
					$camds=$this->aux->buscador; 
		      	$todo.='"CAST(' . $modelos[$i] . '.'.$camds.'' . ' AS VARCHAR(500))"' . " ilike '%" . $valor . "%' OR ";
			}
			for ($i = 0; $i < count($campos); $i++) 
			{
				if (in_array($campos[$i][0]['column_name'], $this->mode_buscador->busqueda)) 
				{
	            	$todo.='"CAST(' . $model . '.' . $campos[$i][0]['column_name'] . ' AS VARCHAR(500))"' . " ilike '%" . $valor . "%' OR ";
	            }
			} 
			$tod = substr($todo, 0, -3);
			
			if(isset($this->mode_buscador->estatus)) $tod.=") AND $model.{$this->mode_buscador->estatus} != 0";
			else $tod.=") AND $model.estatus !=0 ";

			$tipo_usuario=$this->Interfaz->id($this->Session->read('tipo_usuario'));
			$tienda_id=$this->Interfaz->id($this->Session->read('tienda_id'));
			if($tipo_usuario!=1 and $tipo_usuario!=3)
			{
				if($model=='Productor' or $model=='Usuario' or $model=='Funcionario')
				{
					$tod.=' AND "'.$model.'.tienda_id"='.$tienda_id;
				}
			}
			$condicion = array("or" => array($tod));			
			$data = $this->mode_buscador->find('all', array('conditions' => $condicion, 'order' => $ord_bus));
		}
		
		return $data;
	}
	else
	{
		$this->Vista->mensaje('No existe Informacion necesaria','ALERTA');
		$this->render("../".PRINCIPAL."/imagen");
	}
}

function _sesion_plana($condicion=null)
{ 
	if($condicion=='plana')
	{
		$fichero = ROOT.DS.APP_DIR.DS.'tmp'.DS.'sessions'.DS.$_SERVER['REMOTE_ADDR'];
		@$codificado =  file_get_contents( $fichero);
		$fichero_resultado = "<? \n";
		$fichero_resultado .= '$ar_usuario_id=\''.$this->Session->read('usuario_id')."'; \n";
		$fichero_resultado .= '$ar_sistema_id=\''.$this->Session->read('sistema_id')."'; \n";
		$fichero_resultado .= '$ar_tipo_usuario=\''.$this->Session->read('tipo_usuario')."'; \n";
		$fichero_resultado .= '$ar_sesion_id=\''.$this->Session->read('sesion_id')."'; \n";
		$fichero_resultado .= '$ar_nombre_usuario=\''.$this->Session->read('nombre_usuario')."'; \n";
		$fichero_resultado .= '$ar_cedula_usuario=\''.$this->Session->read('cedula_usuario')."'; \n";
		$fichero_resultado .= '$ar_tlf_usuario=\''.$this->Session->read('tlf_usuario')."'; \n";
		$fichero_resultado .= '$ar_username=\''.$this->Session->read('username')."'; \n";
		$fichero_resultado .= '$ar_hora_acceso=\''.$this->Session->read('hora_acceso')."'; \n";
		$fichero_resultado .= '$ar_Autenticado=\''.$this->Session->read('Autenticado')."'; \n";
		$fichero_resultado .= '$ar_tienda_id=\''.$this->Session->read('tienda_id')."'; \n";
		$fichero_resultado .= '$ar_nombre_tienda=\''.$this->Session->read('nombre_tienda')."'; \n";
		$fichero_resultado .= '$ar_es_central=\''.$this->Session->read('es_central')."'; \n";
		$fichero_resultado .= '$ar_Config_userAgent=\''.$this->Session->read('Config_userAgent')."'; \n";
		$fichero_resultado .= '$ar_Config_time=\''.$this->Session->read('Config_time')."'; \n";
		$fichero_resultado .= '$ar_Config_countdown=\''.$this->Session->read('Config_countdown')."'; \n";
		$fichero_resultado .= '$ar_x=\''.$this->Session->read('x')."'; \n";
		$fichero_resultado .= '$ar_y=\''.$this->Session->read('y')."'; \n";
		$fichero_resultado .= '?>';
		@file_put_contents( $fichero, $fichero_resultado );
  		include(ROOT.DS.APP_DIR.DS.'tmp'.DS.'sessions'.DS.$_SERVER['REMOTE_ADDR']);
		$this->permisos($this->Interfaz->id($this->Session->read('sistema_id')),$this->Interfaz->id($this->Session->read('usuario_id')));
		
		$this->definicion_estandar();
	}
	else if($condicion=='php')
	{
        @include(ROOT.DS.APP_DIR.DS.'tmp'.DS.'sessions'.DS.$_SERVER['REMOTE_ADDR']);
		$this->Session->write('usuario_id',$ar_usuario_id);
		$this->Session->write('sistema_id',$ar_sistema_id);
		$this->Session->write('tipo_usuario',$ar_tipo_usuario);
		$this->Session->write('sesion_id',$ar_sesion_id);
		$this->Session->write('nombre_usuario',$ar_nombre_usuario);
		$this->Session->write('cedula_usuario',$ar_cedula_usuario);
		$this->Session->write('tlf_usuario',$ar_tlf_usuario);
		$this->Session->write('username',$ar_username);
		$this->Session->write('hora_acceso',$ar_hora_acceso);
		$this->Session->write('Autenticado',$ar_Autenticado);
		$this->Session->write('tienda_id',$ar_tienda_id);
		$this->Session->write('nombre_tienda',$ar_nombre_tienda);
		$this->Session->write('es_central',$ar_es_central);
		$this->Session->write('Config_userAgent',$ar_Config_userAgent);
		$this->Session->write('Config_time',$ar_Config_time);
		$this->Session->write('Config_countdown',$ar_Config_countdown);
		$this->Session->write('x',$ar_x);
		$this->Session->write('y',$ar_y);
		$this->permisos($this->Interfaz->id($ar_sistema_id),$this->Interfaz->id($ar_usuario_id));
		$this->definicion_estandar();
	}
}

function _principal_ayuda_funciones($sitio,$archivo,$ruta)
{
	$this->layout = 'ajax';
	$ruta=unserialize(base64_decode($ruta));
	if($sitio=='helper')
	{
		$ruta=$ruta.'/'.$archivo.'Helper.php';
		$title="Helper->".$archivo;
	}
	else if($sitio=='controller')
	{
		$ruta=$ruta.'/'.$archivo.'Controller.php';
		$title="Controller->".$archivo;
	}
	else if($sitio=='component')
	{
		$ruta=$ruta.'/'.$archivo.'Component.php';
		$title="Component->".$archivo;
	}
	else if($sitio=='js')
	{
		$ruta=$ruta.'/'.$archivo.'.js';
		$title="Javascritp->".$archivo;
	}
	else if($sitio=='css')
	{
		$ruta=$ruta.'/'.$archivo.'.css';
		$title="css->".$archivo;
	}
	else
	{
		$ruta='';
		$title="Documentacion";
	}

	echo "<script type='text/javascript'>
			document.getElementById('ayudabottomdiv').innerHTML='&nbsp';
			document.getElementById('titleayudadesarrolloss').innerHTML='$title';
		</script>";
	$this->set('s',$sitio);
	$this->set('r',$ruta);      
}


public function _principal_ayuda_documentacion($funtion,$ruta) 
{
	$this->layout = 'ajax';
	$ruta=unserialize(base64_decode($ruta));
	$this->set('r',$ruta);
	$this->set('f',$funtion);
}

public function pr($data=null) 
{
	echo '<pre>';print_r($data);echo '</pre>';	
}

public function permisos($sistema=null,$usuario=null)
{
	if(empty($sistema) && empty($usuario))
	{
		$permisos=null;
	}
	else
	{
		$sql="select p.permiso,s.nombre_var as sistema,ms.nombre_var as modulo, asi.nombre_var as accion, os.nombre_var as opcion from permisos p, modulo_accion_opcions mao, opcion_sistemas os, sistema_modulo_accions sma, accion_sistemas asi, sistema_modulo_sistemas sms, modulo_sistemas ms, sistemas s where p.modulo_accion_opcion_id=mao.id and mao.opcion_sistema_id=os.id and mao.sistema_modulo_accion_id=sma.id and sma.accion_sistema_id= asi.id and sma.sistema_modulo_sistema_id=sms.id and sms.modulo_sistema_id=ms.id and sms.sistema_id=s.id and mao.estatus=1 and os.estatus=1 and sma.estatus=1 and asi.estatus=1 and sms.estatus=1 and ms.estatus=1 and s.estatus=1 and p.usuario_id=$usuario and s.id=$sistema order by 2,3,4,5";
		$permi=$this->Usuario->query($sql);
		if(count($permi)>0)
		{
			for($i=0;$i <count($permi);$i++)
			{
				$permisos[$permi[$i][0]['modulo']][$permi[$i][0]['accion']][$permi[$i][0]['opcion']]=$permi[$i][0]['permiso'];
			}
		}
		else
		{
			$permisos=null;
		}
	}
	$this->Session->delete('permisos_sistema');
	$this->Session->write('permisos_sistema',$permisos);
	return $permisos;
}

/*
	Funcion que setea los permisos del menu principal
*/
public function permisos_menu($id_sistema=null)
{
	$id_sistema= $this->Interfaz->id($this->Session->read('sistema_id'));
	if(isset($id_sistema))
	{
		@$permisos=$this->Session->read('permisos_sistema');
		$aux= $this->Sistema_modulo_sistema->find('all',array('fields'=> array("Modulo_sistema.nombre_var","Modulo_sistema.nombre"),'conditions'=> array("Sistema_modulo_sistema.sistema_id"=>$id_sistema)));
		for($i=0; $i < count($aux); $i++)
		{
			if(isset($permisos[$aux[$i]['Modulo_sistema']['nombre_var']]['ESTATUS']['ESTATUS'])) $p=$permisos[$aux[$i]['Modulo_sistema']['nombre_var']]['ESTATUS']['ESTATUS'];
			else  $p=0;
			$this->set("P_".$aux[$i]['Modulo_sistema']['nombre_var'],$p);
		}			
		$r=1;
	}
	else
	{
		$r=0;
	}
	return $r;
}

/*
Funcion que busca el permiso individual de un modulo y setea los permisos de las acciones que tiene el modulo en especifico
*/
public function permisos_menu_individual($modulo=null,$msj=null)
{
	$p=0; 
	if($this->validar())
	{
		if(!isset($msj)) $msj="No tiene Permisos para realizar esta Operacion!!!";
		if(isset($modulo))
		{
			$this->set('MODULO',$modulo);
			@$permisos=$this->Session->read('permisos_sistema');
			//$this->pr($permisos);
			$modulofinal=str_replace(' ','_',$this->Utilitario->mayuscula($modulo));
			if(isset($permisos[$modulofinal]['ESTATUS']['ESTATUS'])){
				$p=$permisos[$modulofinal]['ESTATUS']['ESTATUS'];
				if($p==1) $this->permisos_acciones($modulo);
			} 
			else  $p=0;
		}
		if($p==0)
		{ 
			$this->set('mostrar',1);
			$this->Vista->mensaje($msj,'SIN PERMISOS');	
			$this->render("../".PRINCIPAL."/mensajes");
		}
	}
	return $p;
}

public function permisos_acciones($accion_ori=null)
{
	if(isset($accion_ori))
	{
		echo "<script type='text/javascript'>document.getElementById('dondepermiso').value='';</script>";
		@$permisos=$this->Session->read('permisos_sistema');
		$accion=str_replace(' ','_',$this->Utilitario->mayuscula($accion_ori));
		$permisos_original=$permisos[$accion];
		//@$this->pr($permisos_original);	
		if(count($permisos_original)>0)
		{
			foreach($permisos_original as $clave => $permisos_orig)
			{
				//$r["P_S_".$clave]=$permisos_orig['ESTATUS'];
				$llave="P_S_".$clave;
				$valor=$permisos_orig['ESTATUS'];
				$this->set("P_S_".$clave,$permisos_orig['ESTATUS']);
				echo "<script type='text/javascript'>
					var permi= document.getElementById('dondepermiso').value;
					permi= permi+'$llave=$valor|';
					document.getElementById('dondepermiso').value=permi;
					</script>";
				$this->permisos_opciones($accion_ori,$clave);
			}

			//Aqui deberia serializar,(la coma la puso el TSU J.R) tengo que pensarlo(ING. D.A.)
		}
		//@$this->pr($r);	
		$r=1;
	}
	else
	{
		$r=0;
	}
	return $r;
}

public function permisos_opciones($accion_ori,$opciones=null)
{
	$r=0;
	if(!isset($msj)) $msj="No tiene Permisos para realizar esta Operacion!!!";
	if(isset($opciones))
	{
		@$permisos=$this->Session->read('permisos_sistema');
		$accion_ori=str_replace(' ','_',$this->Utilitario->mayuscula($accion_ori));
		$opciones=str_replace(' ','_',$this->Utilitario->mayuscula($opciones));
		$permisos_original=$permisos[$accion_ori][$opciones];
		if(count($permisos_original)>0)
		{
			foreach($permisos_original as $clave => $permisos_orig)
			{
				if($clave!='ESTATUS')
				{
					$a[$clave]=$permisos_orig;
					$this->set("P_".$clave,$permisos_orig);
					$llave="P_".$clave;
					$valor=$permisos_orig;
					echo "<script type='text/javascript'>
						var permi= document.getElementById('dondepermiso').value;
						permi= permi+'$llave=$valor|';
						document.getElementById('dondepermiso').value=permi;
						</script>";
				}
				
			}
			//@$this->pr($a);
			$r=1;
		}
	}
	else
	{
		$r=0;
	}
	return $r;
}

/*
Funcion que busca el permiso individual de una Accion Para un modulo
*/
public function permisos_accion_individual($modulo=null,$accion=null,$msj=null)
{
	$p=0; 
	if($this->validar())
	{
		if(!isset($msj)) $msj="No tiene Permisos para realizar esta Operacion!!!";
		if(isset($modulo) and isset($accion))
		{
			$modulo=str_replace(' ','_',$this->Utilitario->mayuscula($modulo));
			$accion=str_replace(' ','_',$this->Utilitario->mayuscula($accion));
			@$permisos=$this->Session->read('permisos_sistema');				
			if(isset($permisos[$modulo][$accion]['ESTATUS'])){
				$p=$permisos[$modulo][$accion]['ESTATUS'];
				$this->permisos_opciones($modulo,$accion);
			} 
			else  $p=0;
		}
		else
		{
			$p=0;
		}
		if($p==0)
		{ 
			$this->set('mostrar','0');
			$this->Vista->mensaje($msj,'SIN PERMISOS');	
			$this->render("../".PRINCIPAL."/mensajes");
		}
	}	
	return $p;
}

/*
Funcion que busca el permiso individual de una Opcion para una Accion en un modulo
*/
public function permisos_opcion_individual($modulo=null,$accion=null,$opcion=null,$msj=null)
{
	$p=0; 
	if($this->validar())
	{
		if(!isset($msj)) $msj="No tiene Permisos para realizar esta Operacion!!!";
		if(isset($modulo) and isset($accion) and isset($opcion))
		{
			$this->permisos_opciones($modulo,$accion);
			$modulo=str_replace(' ','_',$this->Utilitario->mayuscula($modulo));
			$accion=str_replace(' ','_',$this->Utilitario->mayuscula($accion));
			$opcion=str_replace(' ','_',$this->Utilitario->mayuscula($opcion));
			@$permisos=$this->Session->read('permisos_sistema');			
			if(isset($permisos[$modulo][$accion][$opcion])) $p=$permisos[$modulo][$accion][$opcion];
			else  $p=0;
		}
		else
		{
			$p=0;
		}
		if($p==0)
		{ 
			$this->set('mostrar','0');
			$this->Vista->mensaje($msj,'SIN PERMISOS');	
			$this->render("../".PRINCIPAL."/mensajes");
		}
	}	
	return $p;
}

public function obtener_permisos($opciones=null,$msj=null,$render=1)
{
	$r=0;
	if($this->validar())
	{
		if(!isset($msj)) $msj="No tiene Permisos para realizar esta Operacion!!!";
		if(count($opciones)>0)
		{
			if(empty($opciones[1]))$opciones[1]='ESTATUS';
			if(empty($opciones[2]))$opciones[2]='ESTATUS';
			$opciones[0]=str_replace(' ','_',$this->Utilitario->mayuscula($opciones[0]));
			$opciones[1]=str_replace(' ','_',$this->Utilitario->mayuscula($opciones[1]));
			$opciones[2]=str_replace(' ','_',$this->Utilitario->mayuscula($opciones[2]));
			$permisos=$this->Session->read('permisos_sistema');
			if(isset($permisos[$opciones[0]][$opciones[1]][$opciones[2]]) && is_numeric($permisos[$opciones[0]][$opciones[1]][$opciones[2]]))
				$r=$permisos[$opciones[0]][$opciones[1]][$opciones[2]];
			else $r=0;
		}
		else
		{
			$r=0;
		}
		if($r==0)
		{ 
			$this->Vista->mensaje($msj,'SIN PERMISOS');	
			if($render===1)
			{
				$this->render("../".PRINCIPAL."/mensajes");
			}
			else return $r;
		}
		else return $r;
	}
	return $r;
}

public function obtener_permisos_mao($maoid=null,$usu_id=null)
{
	if(isset($maoid) and isset($usu_id))
	{
		$r=$this->Permiso->find('first',array('fields'=>array('Permiso.id','Permiso.permiso'),'conditions'=>array('Permiso.modulo_accion_opcion_id'=>$maoid,'Permiso.usuario_id'=>$usu_id)));
		$permisos=$this->Session->read('permisos_sistema');
		if(isset($r['Permiso']['id']) && $r['Permiso']['id']>0)	$res=$r['Permiso']['permiso'];
		else $res=0;
	}
	else
	{
		$res=0;
	}
	return $res;
}

public function sin_permiso($div=null) 
{
	$p=0;
	if($this->validar())
	{
		$p=1;
		if(isset($div) && ($div==DOCULTO or $div==DVENTANA))
		{
			$this->set('mostrar','0');
		}
		else
		{
			$this->set('mostrar','1');
		}
		$this->Vista->mensaje("El Usuario no Posee Permisos Para realizar esta Operacion",'SIN PERMISOS');	
		$this->render("../".PRINCIPAL."/mensajes");
	}
	return $p;
}

public function bloquear_buscador($tipo=1)
{
	if($tipo==1)
		echo "<script type='text/javascript'>		
		document.getElementById('buscadorindex').disabled = true;
		document.getElementById('buscadorindex').value='BLOQUEADO';
		</script>";
	else
		echo "<script type='text/javascript'>
		document.getElementById('buscadorindex').value='';
		document.getElementById('buscadorindex').disabled = false;
		</script>";
}

public function serializador($datos,$tipo=null) //1 => Deserealiza 2 => Serealizador
{
	if(isset($tipo) && !empty($tipo) && ($tipo==1 || $tipo==2))
	{
		if($tipo==1)
		{
			$a=urldecode($datos);
			$final=unserialize($a);
		}
		else
		{
			$compactada=serialize($datos);
			$final=urlencode($compactada);
		}
	}
	else
	{
		$this->Vista->mensaje('Para usar esta funcion debe indicar un arreglo como primer parametro y un tipo (1 o 2) como segundo parametro','DATOS INCOMPLETOS');
		$final=null;
	}
	return $final;
}

public function definicion_estandar()
{
	$id_sistema= $this->Interfaz->id($this->Session->read('sistema_id'));
	if(isset($id_sistema) && $id_sistema >0 ){
		$ds=$this->Sistema->find('first',array('conditions'=>array('Sistema.id'=>$id_sistema)));
		$sistema=$ds['Sistema']['nombre'];
		$parametros= $this->Configuracion->find('all',array('conditions'=>array('estatus'=>1)));
		foreach($parametros as $datos){
			if(!isset($_SESSION[$datos['Configuracion']['campo']])) { 
				if(in_array($datos['Configuracion']['campo'],array("EMAIL_FROM_NAME","SYSTEM_NAME_NOTIF_ERROR"))) $this->Session->write($datos['Configuracion']['campo'], $sistema);
				else $this->Session->write($datos['Configuracion']['campo'], $datos['Configuracion']['valor']);
			};
		}
		$this->Session->write('listaCorreos', $this->obtenerListaNotificacion());
		$this->CorreoPlantilla = ClassRegistry::init('CorreoPlantilla');
		$d=$this->CorreoPlantilla->find('first',array('conditions'=>array('CorreoPlantilla.codigo'=>'ERROR_SQL')));
		$this->Session->write('dataPlantilla', $d['CorreoPlantilla']);
		$d=$this->CorreoPlantilla->find('all',array('conditions'=>array('CorreoPlantilla.estatus'=>1)));
		foreach($d as $indice => $datos){
				$plantillas[$datos['CorreoPlantilla']['codigo']] = $datos['CorreoPlantilla'];
		}
		$this->Session->write('plantillas', $plantillas);
		$id_usuario= $this->Interfaz->id($this->Session->read('usuario_id'));
		$this->UsuarioPunto = ClassRegistry::init('UsuarioPunto');
		$lis_tiendas= $this->UsuarioPunto->find('all',array('fields'=>array('UsuarioPunto.punto_id'),'conditions'=> array('UsuarioPunto.usuario_id'=> $id_usuario,'UsuarioPunto.estatus'=>1)));
    $this->Session->write('tiendas_disponibles', $lis_tiendas);                      
	}
}

public function obtenerListaNotificacion()
{

        $default = array('original' => array('jesusrodriguez@agropatria.com.ve', 'darwinascanio@agropatria.com.ve', 'juantaborda@agropatria.com.ve', 'juancarrizalez@agropatria.com.ve', 'jecksongarcia@agropatria.com.ve', 'josegregoriodefreitas@agropatria.com.ve', 'elbacampos@agropatria.com.ve'));
        $arrList = explode(';', $_SESSION['LISTA_NOTIFICAR_ERROR']);
        foreach ($arrList as $address) {
            $arr_users_error['original'][] = trim($address);
        }
        return ($arr_users_error) ? $arr_users_error : $default;
}


/*
public function obtenerPlantillaError()
{
	$d=$this->CorreoPlantilla->find('first',array('conditions'=>array('CorreoPlantilla.codigo'=>'ERROR_SQL')));
	$this->set('dataPlantilla',$d);
	$this->set('listaCorreos',$this->obtenerListaNotificacion());
}
*/

public $uses = array('Usuario','Funcionario','Organizacion','Tienda','Estado','Municipio','Parroquia','Logsql','Tipo_usuario','Usuario_sistema','Permiso','Sistema_modulo_sistema','Configuracion','Correo','CorreoPlantilla','Sistema','UsuarioPunto');

}
